lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I am fairly new to programming and i need some help with optimizing.Basically a part of my method does : So i am searching for a Tile in a position which is 1 unit above the current Tile.My problem is that for the whole method it takes 0.1 secs which results in a small hick up..Without Array.Find the method is 0.01 sec... | for ( int i = 0 ; i < Tiles.Length ; i++ ) { x = Tiles [ i ] .WorldPosition.x ; y = Tiles [ i ] .WorldPosition.y ; z = Tiles [ i ] .WorldPosition.z ; Tile topsearch = Array.Find ( Tiles , search = > search.WorldPosition == Tiles [ i ] .WorldPosition + new Vector3Int ( 0,1,0 ) ) ; if ( topsearch.isEmpty ) { // DoMyThing... | Need help for search optimization |
C# | How do i make a application that will produce a random number between 1-10 and then ask the user to guess that number , and if that number is matching the random number tell them if they got it right ! I 'm a student , like super new and was out of class for a few days because of surgery and i can not figure this out f... | namespace GuessingGame { class Program { static void Main ( string [ ] args ) { int min = 1 ; int max = 10 ; Random ranNumberGenerator = new Random ( ) ; int randomNumber ; randomNumber = ranNumberGenerator.Next ( min , max ) ; Console.WriteLine ( `` Guess a random number between 1 and 10 . `` ) ; Console.ReadLine ( ) ... | Random Generator Questions |
C# | I have the following situation : A constructor takes 6 values.Some of them have default values , some not.And I want to be able to call all possible combinations without having to write always all 6 parameters . Besides doing this with method overloading ( which would be tedious ) , is there a more elegant solution ? | # pseudocode # Foo ( int a , int b=2 , int c=3 , int d=4 , int e=5 , int f ) { } # pseudocode # Foo f1 = new Foo ( a=1 , d=7 , f=6 ) ; # pseudocode # Foo f2 = new Foo ( a=1 , b=9 , d=7 , f=6 ) ; | How can method overloading be avoided ? |
C# | While reviewing a PR today I saw this in a class : I suspected that the developer meant thisI was surprised that this even complied so I tried it myself and found that this is legal code and it ends up doing the same thing.My question is : Is there any subtle ( or not so subtle ) difference between these two ? | public bool ? Selected { get ; set ; } //question mark in front of property name public bool ? Selected { get ; set ; } //question mark at end of type | What is the difference between bool ? MyProperty and bool ? MyProperty |
C# | Let 's say I have the following enum : I 'm wondering if there is a way to iterate through all the members of Colors to find the member names and their values . | public enum Colors { White = 10 , Black = 20 , Red = 30 , Blue = 40 } | Is there a way to iterate and reflect the member names and values contained in enumerations ? |
C# | Currently I 'm doing the following to detect what Microsoft Band model the user has : The reason for this approach is because the version of the Band 1 firmware is higher than that of the Band 2 . This makes sense from an engineering perspective but can potentially lead to a conflict once the Band 2 reaches 10+Band 1 u... | FirmwareVersion = await SelectedBand.GetFirmwareVersionAsync ( ) ; BandModel = int.Parse ( FirmwareVersion.Split ( ' . ' ) [ 0 ] ) < 10 ? 2 : 1 ; | How to detect Microsoft Band Version |
C# | Question is very short , but I did n't found a solution.Assume we have the class hierarchyIs it possible to override A.Print in C class ? I tried to do it as explicit interface implementation : but here I get an error : ' A ' in explicit interface declaration is not an interfaceI think it 's not possible at all , but w... | public abstract class A { public virtual string Print ( ) { return `` A '' ; } } public class B : A { public virtual new string Print ( ) { return `` B '' ; } } public class C : B { public override string Print ( ) { return `` C '' ; } } string A.Print ( ) { return `` C '' ; } | Override overlapped method |
C# | I have a few classes i ca n't change . They have one property Prop3 in common : Now I want to acces this property without knowing the type . I thought of using a Interface : But this code throws a invalid cast exception : | public class c1 { public string Prop1 { get ; set ; } public string Prop2 { get ; set ; } public string Prop3 { get ; set ; } } public class c2 { public string Prop2 { get ; set ; } public string Prop3 { get ; set ; } } public class c3 { public string Prop5 { get ; set ; } public string Prop3 { get ; set ; } } public i... | Interface casting |
C# | I have a list of objects with multiple properties in it . Here is the object.Now in my code , I have a giant list of these , hundreds maybe a few thousand.Each data point object belongs to some type of scanner , and has a scan date . I want to remove any data points that were scanned on the same day except for the last... | public class DataPoint { private readonly string uniqueId ; public DataPoint ( string uid ) { this.uniqueId = uid ; } public string UniqueId { get { return this.uniqueId ; } } public string ScannerID { get ; set ; } public DateTime ScanDate { get ; set ; } } this.allData = this.allData.GroupBy ( g = > g.ScannerID ) .Se... | Remove all but 1 object in list based on grouping |
C# | I have following simple code : How can I calculate min , max , avg , etc . of all executed tasks ? The task class does n't have property like `` executedMilliseconds '' | var tasks = statements.Select ( statement = > _session.ExecuteAsync ( statement ) ) ; var result = Task.WhenAll ( tasks ) .Result ; [ ... ] | Get statistic of executed tasks in C # |
C# | I am using ASP.NET MVC5 and MS SQL 2008 and EntityFramework 6 , in my application i have a class Experiences that will allow the clients to add details of their experiences from period till period : the FromDate format will be MMM yyyy , example Jan 2009 , Oct 2010 , ... etcthe ToDate format will be either MMM yyyy or ... | public class Experience { public int Id { get ; set ; } public string Title { get ; set ; } public string Company { get ; set ; } public string FromDate { get ; set ; } public string ToDate { get ; set ; } public string Description { get ; set ; } } public class Period : IComparable { public Period ( ) { this.Month= ''... | linking entityframework to a new Sql DataType |
C# | I 'm using XDocument to cache a list of files.In this example , I used XText , and let it automatically escape characters in the file name , such as the & with & amp ; In this one , I used XCData to let me use a literal string rather than an escaped one , so it appears in the XML as it would in my application.I 'm wond... | < file id= '' 20 '' size= '' 244318208 '' > a file with an & amp ; ersand.txt < /file > < file id= '' 20 '' size= '' 244318208 '' > < ! [ CDATA [ a file with an & ersand.txt ] ] > < /file > | What is the proper way to store a file name in XML ? |
C# | I 'm not really sure if I have the correct title for this Q. anyway I 'm trying to parse a delimited string into a list of Enum elements : Given an input of : I would like to output only the parts that exists in MyEnum ( ignoring the case ) : [ MyEnum.Enum2 , MyEnum.Enum3 ] How do I return `` nothing '' from the Select... | public enum MyEnum { Enum1 , Enum2 , Enum3 } string s = `` Enum2 , enum3 , Foo , '' ; IEnumerable < MyEnum > sl = s.Split ( new char [ ] { ' , ' , ' ' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( a = > { if ( Enum.TryParse ( a , true , out MyEnum e ) ) return e ; else return nothing ? ? ? } ) IEnumerable < MyE... | Select only if condition in LINQ |
C# | I 'm looking at some asynchronous programming in C # and was wondering what the difference would be between these functions that does the exact same thing and are all awaitable.My guess is that the first is the correct way to do things , and the code is n't executed until you try to get the result from the returned Tas... | public Task < Bar > GetBar ( string fooId ) { return Task.Run ( ( ) = > { var fooService = new FooService ( ) ; var bar = fooService.GetBar ( fooId ) ; return bar ; } ) ; } public Task < Bar > GetBar ( string fooId ) { var fooService = new FooService ( ) ; var bar = fooService.GetBar ( fooId ) ; return Task.FromResult ... | What is the difference between these awaitable methods ? |
C# | At the bottom of this post is an example of how a solution might look , although clearly the example is invalid because it used BaseNode and BaseEdge without providing types when inheriting.I 'm trying to create an abstract graph class , where both the node class and the edge class must also be abstract . Individual im... | abstract class Graph < TNode , TEdge > where TNode : BaseNode < TEdge > where TEdge : BaseEdge < TNode > { TNode root ; List < TNode > nodes ; List < TEdge > edges ; public abstract float process ( ) ; } abstract class BaseNode < TEdge > // THIS HERE IS THE PROBLEM where TEdge : BaseEdge { List < TEdge > inputs ; publi... | Interdependent Generic Classes ? |
C# | I have a code that I want to count the number of appearing each letter in alphabet in the input string.I used a dictionary < char , int > to have a key for each letter and a value as the count of appearance.So , how to have a list of ' a ' to ' z ' to use as keys ? I 've tried this : Is it a better way to have the list... | Dictionary < char , int > alphabetCounter = new Dictionary < char , int > ( ) ; for ( char ch = ' a ' ; ch < = ' z ' ; ch++ ) alphabetCounter [ ch ] = 0 ; | how to have a list of ' a ' to ' z ' ? |
C# | You can use to create a new List and add 2 items . The { `` 1 '' , `` 2 '' } -part only works because List < T > has implemented a Add ( ) method.my question : is { } something like a operator and can it be overloaded e.g . to add items twice | List < string > sList = new List < string > ( ) { `` 1 '' , `` 2 '' } ; | Is there a { } Operator ? |
C# | When dealing with empty sequences , I was surprised to find out that the behavior for min or max is different depending on whether the source collection elements are of value type or of reference type : This difference of behaviors is nicely seen on .NET Core implementation of Enumerable extensions.This , however , is ... | var refCollection = new object [ 0 ] ; var valCollection = new int [ 0 ] ; var nullableCollection = new int ? [ 0 ] ; var refMin = refCollection.Min ( x = > x ) ; // nullvar valMin = valCollection.Min ( ) ; // InvalidOperationExceptionvar nullableMin = nullableCollection.Min ( ) ; // null | Why is Enumerable Min or Max inconsistent between collections of reference and value types ? |
C# | I have many Azure classes containing fields for date and modified by tracking . Fields such as : I want to avoid repetition so I was considering creating a class to contain these such as this : For my data classes then instead of having them inherit from TableServiceEntity I would like to set these up as follows : Is t... | [ DisplayName ( `` Created By '' ) ] public string CreatedBy { get ; set ; } [ DisplayName ( `` Modified By '' ) ] public string ModifiedBy { get ; set ; } public class TableServiceEntityRowInfo : TableServiceEntity { [ DisplayName ( `` Created By '' ) ] public string CreatedBy { get ; set ; } [ DisplayName ( `` Modifi... | Is this a valid way to simplify my inherited classes ? |
C# | Is there a way I can convert a nullable reference type to non-nullable reference type in the below example less verbosely ? This would be for when the nullable reference flag for the compiler is enabled.When the nullable reference type is null , I would like it to throw an exception . | Assembly ? EntryAssemblyNullable = Assembly.GetEntryAssembly ( ) ; if ( EntryAssemblyNullable is null ) { throw new Exception ( `` The CLR method of Assembly.GetEntryAssembly ( ) returned null '' ) ; } Assembly EntryAssembly = EntryAssemblyNullable ; var LocationNullable = Path.GetDirectoryName ( EntryAssembly.Location... | Converting a nullable reference type to a non-nullable reference type , less verbosely |
C# | The thing I am conerned about is will the first expression always be run ( setting expenseCode in the process ) before the second operation ? | int expenseCode ; if ( int.TryParse ( sourceRecord.ExpenseCode , out expenseCode ) & & _ExpenseCodeLookup.ContainsKey ( expenseCode ) ) { destRow.PROFIT_CENTER_NAME = _ExpenseCodeLookup [ expenseCode ] ; } else destRow.PROFIT_CENTER_NAME = `` Unknown '' ; | Will this if statment cause bad things to happen ? |
C# | Client : Basically sends `` 1 '' to the Index action in the Client controller.Here is the Controller : The result from the Client is just `` Result : ; '' . The debug output from the controller is also `` Result : ; '' . This means that the data is lost somewhere between the client and the site . But when I debug , Vis... | WebClient wc = new WebClient ( ) ; try { string json = wc.UploadString ( `` http : //localhost:50001/Client/Index '' , `` 1 '' ) ; dynamic receivedData = JsonConvert.DeserializeObject ( json ) ; Console.WriteLine ( `` Result : { 0 } ; '' , receivedData.data ) ; } catch ( Exception e ) { Console.WriteLine ( `` Oh bother... | MVC website does n't receive string from client |
C# | For example , the difference between this code and thatWhich one is correct or faster working ? And just call this method need to await or just a task ? | public Task < IList < NewsSentimentIndexes > > GetNewsSentimentIndexes ( DateTime @ from , DateTime to = new DateTime ( ) , string grouping = `` 1h '' ) { var result = _conf.BasePath .AppendPathSegment ( `` news-sentiment-indexes '' ) .SetQueryParams ( new { from = from.ToString ( `` s '' ) , to = to.ToString ( `` s ''... | What is the difference between using only async Task and Task ? |
C# | Throw Expressions work in this case : But why does n't this compile too ? | string myStr ; public MyObj ( string myStr ) = > this.myStr = myStr ? ? throw new ArgumentNullException ( `` myStr '' ) ; bool isRunning ; public void Run ( ) = > isRunning = ! isRunning || throw new InvalidOperationException ( `` Already running '' ) ; | Throw Expressions not working for Boolean expressions ? |
C# | Why does the following asynchronous recursion fail with StackOverflowException , and why is it happening exactly at the last step , when the counter becomes zero ? Output : I 'm seeing this with .NET 4.6 installed . The project is a console app targeting .NET 4.5.I understand that the continuation for Task.Yield may ge... | static async Task < int > TestAsync ( int c ) { if ( c < 0 ) return c ; Console.WriteLine ( new { c , where = `` before '' , Environment.CurrentManagedThreadId } ) ; await Task.Yield ( ) ; Console.WriteLine ( new { c , where = `` after '' , Environment.CurrentManagedThreadId } ) ; return await TestAsync ( c-1 ) ; } sta... | Unexpected stack overflow despite yielding |
C# | I 'm setting up an uploader for my Web Application which consists of 2 file input elements wherein the first file input will get the image and store it to the list of images variableand the second one will get the pdf and store it to the list of pdf files variable . the approach that I did to it is to store the file ob... | [ HttpPost ( `` SaveNewData '' ) , DisableRequestSizeLimit ] [ Consumes ( `` multipart/form-data '' ) ] public ActionResult SaveNewData ( [ FromForm ] MyModelUpload modelUpload ) { var modelUploaded = modelUpload ; return Ok ( ) ; } public class MyModelUpload { public IFormFile [ ] imageFile { get ; set ; } public stri... | Angular 6 - Multiple file input in single form group |
C# | I wrote an application using ASP.NET MVC 5 framework . I am using a two way binding between the views and the ViewModels.Since I am using two way binding , I get the benefit of client and server side validation which is cool . However , when I send a POST request to the server , and the request handler throws an except... | [ ImportModelStateFromTempData ] public ActionResult show ( int id ) { var prsenter = new UserProfileDetailsPresenter ( id ) ; ModelStateDictionary tmp = TempData [ `` Support.ModelStateTempDataTransfer '' ] ; if ( tmp ! = null ) { // Some how map tmp to prsenter } return View ( prsenter ) ; } [ HttpPost ] [ ValidateAn... | How can I manually bind data from a ModelStateDictionary to a presentation model with ASP.NET MVC ? |
C# | The compiler should translate this code : to two methods that have the same name and signature but differ only by their return type , e.g.However , we are not allowed to have methods that differ only by their return type . What happens behind the curtains ? | public static explicit operator Int64 ( MyNumber n ) { return n.ToInteger ( ) ; } public static explicit operator Double ( MyNumber n ) { return n.ToDouble ( ) ; } public static Int64 ExplicitCast ( MyNumber n ) ... public static Double ExplicitCast ( MyNumber n ) ... | How does the C # compiler handle overloading explicit cast operators ? |
C# | There is a design problem like this . Suppose you have a set of class that implements similar methods but not identical ones.Example : The ClassA has methods like this.Another class , ClassB has the following methods.So the nature of the methods are similar but the return types/ input parameters are different . If I de... | void Add ( string str ) ; void Delete ( string str ) ; List < string > GetInfo ( string name ) ; void Add ( Dictionary Info ) ; void Delete ( string str ) ; Dictionary GetInfo ( string name ) ; | What is the best design I can use to define methods with same name ? |
C# | specifically , is the `` += '' operation atomic ? does it make a difference if i 'm using the 'event ' keyword , or just a plain old delegate ? with most types , its a read , then the `` + '' operator , and then a write . so , it 's not atomic . i 'd like to know if there 's a special case for delegates/events.is this ... | Action handler ; object lockObj ; public event Action Handler { add { lock ( lockObj ) { handler += value ; } } remove { lock ( lockObj ) { handler -= value ; } } } | is it thread safe to register for a c # event ? |
C# | In a dynamic expression dynamic x , is there a reason/explanationwhy the surrounding expression ( e.g . foo ( x ) ) gets dynamic as well ? Consider : I was assuming that the compiler could resolve ( at compile time ) that foo ( object ) is to be called . However , hovering with the mouse over foo ( x ) reveals that the... | static string foo ( object x ) { } static void Main ( ) { dynamic x = null ; foo ( x ) ; // foo ( x ) is a dynamic expression } foo ( ( object ) x ) ; | Why is the surrounding type of a dynamic expression not statically resolved in C # ? |
C# | I 'm working on simple client-server solution where client can send different types of commands to server and get specific results . Commands can have different properties . What I 'd like to have is an architecture where a specific command handler could be chosen based on the type of the command it handles . I created... | public interface ICommand { } public class CommandA : ICommand { public string CustomProperty { get ; set ; } } public class CommandB : ICommand { } public interface ICommandHandler { bool CanHandle ( ICommand command ) ; IReply Handle ( ICommand command ) ; } public abstract class CommandHandlerBase < TCommand > : ICo... | Replace casting with better pattern |
C# | Can someone please give me the technical reason why < clear > < /clear > is invalid in app.config vs < clear / > It 's typically used like this : Problem is I 'm using an installer product ( InstallShield ) with does xml transformation to app.config files , and it 's changing < clear / > to < clear > < /clear > This br... | < connectionStrings > < clear/ > < add etc ... .. / > < /connectionStrings > | Why is < clear > < /clear > not the same as < clear / > in app.config ? |
C# | First of all , I think I have to apologize for not having that much knowledge of regular expressions ( yet ) .I have searched and searched , but have n't found a solution that matches my specific challenge here.Now here comes the question : I am currently experimenting with the development of a parser ( meaning to writ... | -3 = ( 0 - 3 ) 5 * -3 = 5 * ( 0 - 3 ) ( 5 -- 5 ) -3 = ( 5 - ( 0 - 5 ) ) - 3 expressionBuffer = `` - ( 1-2 ) -3 '' ; expressionBuffer = Regex.Replace ( expressionBuffer , `` - '' , `` MINUS '' ) ; MINUS ( 1 MINUS 2 ) MINUS 3 expressionBuffer = Regex.Replace ( expressionBuffer , @ '' ( ? < number > ( ( \d+ ( \.\d+ ) ? ) ... | Regex challenge : changing formats of negative numbers |
C# | I use nager.date to know if a day is a holiday day or a weekend day Saturday and Sunday ) .I need to extract the date ( starting from today or any other date ) after 5 working days.The problem of this code is that if the last else occurs , it add me 1 day but without doing any other check.For example : If the start dat... | DateTime date1 = new DateTime ( 2019 , 12 , 23 ) ; int i = 0 ; while ( i < 5 ) { if ( DateSystem.IsPublicHoliday ( date1 , CountryCode.IT ) || DateSystem.IsWeekend ( date1 , CountryCode.IT ) ) { date1 = date1.AddDays ( 1 ) ; } else { date1= date1.AddDays ( 1 ) ; i++ ; } } | Find next 5 working days starting from today |
C# | Here is the scenario My question is to know if i should declare the method close ( ) in HttpConnection class with an override or virtual keyword since it overrides and is overridden at the same time . | public class Connection { public virtual void close ( ) { /*Some code */ } } public interface IHttpRelay { void close ( ) ; } public class HttpConnection : Connection , IHttpRelay { public /*keyword*/ void close ( ) { base.close ( ) ; } } public class Http : HttpConnection { public override void close ( ) { /*Some code... | Comment on a method that overrides and is overridden at the same time in C # ? |
C# | I am trying to delay an animation of a custom control based on a binding value . In the example below , I ’ d like the animation to start 5 seconds after the “ SelectedAndHit ” visual state is selected . However , it doesn ’ t seem possible to use template binding within the VisualStateManage . Is TemplateBinding suppo... | < local : ButtonEx x : Name= '' Button01 '' AnimationBeginTime= '' 00:00:05 '' / > public TimeSpan AnimationBeginTime { get { return ( TimeSpan ) base.GetValue ( ButtonEx.AnimationBeginTimeProperty ) ; } set { base.SetValue ( ButtonEx.AnimationBeginTimeProperty , value ) ; } } public static readonly DependencyProperty ... | Is Databinding or TemplateBinding supported within the VisualStateManager ? |
C# | I find that I am using a lot of join queries , especially to get statistics about user operations from my database . Queries like this are not uncommon : My app is still not active , so I have no way of judging if these queries will be computationally prohibitive in real-life . My query : Is there a limit to when doing... | from io in db._Owners where io.tenantId == tenantId join i in db._Instances on io.instanceId equals i.instanceId join m in db._Machines on i.machineId equals m.machineId select ... | Join queries and when it 's too much |
C# | How is following possible ? Question is , how is x scoped inside each case without any visible blocks . meanwhile , variable invalid cant be declared in different switch cases . it has to be inside a block.if there is no block then following scoping of variables would be impossible.if there is invisible block for each ... | switch ( param.ParameterType ) { case Type x when x == typeof ( byte ) : int invalid ; break ; case Type x when x == typeof ( short ) : int invalid ; break ; case Type x when x == typeof ( int ) : break ; case Type x when x == typeof ( long ) : break ; } { // case byte : Type x ; int invalid ; // break ; // case short ... | How is switch variable declaration scoped ? |
C# | Given an instance of an unknown reference or value type , is there any way to test whether the instance contains the default value for that type ? I envisage something like this ... Of course , this does n't work because GetType returns a runtime type , but I hope that somebody can suggest a similar technique . Thanks ... | bool IsDefaultValue ( object value ) { return value == default ( value.GetType ( ) ) ; } | C # - How to test whether an instance is the default value for its type |
C# | Marshal.SizeOf returns 12 , which is what I assume because the ints are 4 bytes each . If I were to change third to a double instead of an int , I would expect Marshal.SizeOf to return 16 . It does . But if I were to add a fourth that was a double , Marshal.SizeOf returns 24 , when I expect 20 . I could have 10 ints an... | public struct TestStruct { public int first ; public int second ; public int third ; } public struct TestStruct //SizeOf 12 { public int first ; public int second ; public int third ; } public struct TestStruct //SizeOf 16 { public int first ; public int second ; public double third ; } public struct TestStruct //SizeO... | Why is my struct coming out to an unexpected size when I have a double in it ? |
C# | Not sure if this is C # 4+ specific , but just noticed this.Consider the following classes : The call to Foo in Bar , resolves to Foo ( object , object ) .While changing it to : The call to Foo in Bar , resolves to Foo ( object , DayOfWeek ) .My understanding is that it should always resolve as in the second example . ... | class Base { protected void Foo ( object bar , DayOfWeek day ) { } } class Program : Base { protected void Foo ( object bar , object baz ) { } void Bar ( DayOfWeek day ) { Foo ( new { day } , day ) ; } } class Base { } class Program : Base { protected void Foo ( object bar , object baz ) { } protected void Foo ( object... | Overload resolution oddity |
C# | Following class has two method wherein M1 complain ‘ not all code path return a value ’ and M2 doesn ’ t . Question : How does the compiler resolve M2 in context of return value ? How NotImplementedException instance is implicitly casted as int ( if there is any internal compile time resolution ) | class A { int M1 ( ) { } int M2 ( ) { throw new NotImplementedException ( ) ; } } | General C # question |
C# | I stumbled on the fact that the indexer this [ int index ] { get ; } works differently for an array of structs than it does for a List of structs . Namely , that the indexer in the case of an T [ ] returns a reference to the element within the array whereas the indexer in the case of a List < T > returns a copy of the ... | Object IList.this [ int index ] { get { return GetValue ( index ) ; } set { SetValue ( value , index ) ; } } public unsafe Object GetValue ( int index ) { if ( Rank ! = 1 ) throw new ArgumentException ( Environment.GetResourceString ( `` Arg_Need1DArray '' ) ) ; Contract.EndContractBlock ( ) ; TypedReference elemref = ... | Array indexer signature returns object - does it box ? |
C# | I 'm working on a Silverlight project and I 'm trying to understand the differences between the following : | this.Startup += new StartupEventHandler ( this.Application_Startup ) ; this.Startup += this.Application_Startup ; | Are these Startup event handlers identical ? |
C# | I just removed the `` App.xaml '' entirely from my solution and created my own xamlless entry class where I 'm implementing the traditional static Main ( ) method . I 'm instancing a new Application class and setting it up before calling its Run ( ) method , giving it a StartupUri , As well adding to it a new resource-... | public static class Entry { private static readonly Application _application = new Application ( ) ; [ STAThread ] public static void Main ( ) { _application.StartupUri = new Uri ( `` /Eurocentric ; component/Interface/MainWindow.xaml '' , UriKind.Relative ) ; var style = new ResourceDictionary { Source = new Uri ( `` ... | Entirely deleted `` App.xaml '' and created own entry point , What are the consequences ? |
C# | This function returns two different values depending on the way its called.I understand that Closures close over variables , not over values and I expected the values returned from the second call to be the same regardless of how the function is calledHere is the call : The result of using Invoke : The result of using ... | static Func < int , int , int > Sum ( ) { var test = 1 ; return ( op1 , op2 ) = > { test = test + 1 ; return ( op1 + op2 ) + test ; } ; } var mFunc = Sum ( ) ; Console.WriteLine ( `` Calling Sum ( 1,1 ) with Invoke ( ) `` + Sum ( ) .Invoke ( 1 , 1 ) ) ; Console.WriteLine ( `` Calling Sum ( 2,2 ) with Invoke ( ) `` + Su... | Closures behavior |
C# | C # : In C # I have something like this : I assume that the method ImmutableDictionary < K , V > .RemoveRange Method ( IEnumerable < K > ) was introduced since it is much more efficient than series of Remove ( K ) calls . It creates the resulting immutable object only once instead of once for every element from keys to... | IImmutableDictionary < string , string > map = new Dictionary < string , string > { { `` K1 '' , `` V1 '' } , { `` K2 '' , `` V2 '' } , { `` K3 '' , `` V3 '' } , } .ToImmutableDictionary ( ) ; IEnumerable < string > keys = new [ ] { `` K1 , K3 '' } ; map = map.RemoveRange ( keys ) ; let rec removeAll ( map : Map < stri... | RemoveAll from map in F # |
C# | After a day of troubleshooting I 've managed to condense the problem to this tiny piece of code . Could someone explain to me why this does n't work ? I expect [ markets ] to be 0 2 4 6 , [ city ] [ county ] and [ streets ] to be 0 1 2 3 when the messagebox is shown . I 'm looping through items in a foreach loop . If t... | private void pieceoftestcode ( ) { string [ ] county = new string [ 4 ] ; string [ ] city = new string [ 4 ] ; string [ ] markets = new string [ 4 ] ; string [ ] streets = new string [ 4 ] ; string [ ] items = new string [ 4 ] { `` apple '' , `` banana '' , `` pineapple '' , `` juice '' } ; string [ ] value = new strin... | C # strange behaviour in foreach loop |
C# | I had a complete wtf moment when dealing with covariant interfaces.Consider the following : Note : AppleBasket does not inherit from FruitBasket.IBasket is covariant.Later on in the script , you write : ... and as you 'd expect , the output is : HOWEVER , consider the following code : You 'd expect it to output true , ... | class Fruit { } class Apple : Fruit { } interface IBasket < out T > { } class FruitBasket : IBasket < Fruit > { } class AppleBasket : IBasket < Apple > { } FruitBasket fruitBasket = new FruitBasket ( ) ; AppleBasket appleBasket = new AppleBasket ( ) ; Log ( fruitBasket is IBasket < Fruit > ) ; Log ( appleBasket is IBas... | Generic covariance with interfaces - Weird behavioural contradiction between `` is '' and `` = '' operators |
C# | I 'm looking for a best practice for counting how many times each date occurs in a list.For now , I have working code ( just tested ) but I think the way I did is not so good.Anyone who knows a better solution ? | var dates = new List < DateTime > ( ) ; //Fill list herevar dateCounter = new Dictionary < DateTime , int > ( ) ; foreach ( var dateTime in dates ) { if ( dateCounter.ContainsKey ( dateTime ) ) { //Increase count dateCounter [ dateTime ] = dateCounter [ dateTime ] + 1 ; } else { //Add to dictionary dateCounter.Add ( da... | C # Best practice - Counting how many times each date occurs |
C# | Suppose that the scenario does n't allow to implement an immutable type . Following that assumption , I 'd like opinions / examples on how to properly design a type that after it 's consumed , becomes immutable.When ObjectA consumes ObjectAConfig : I 'm not satisfied that this simply works , I 'd like to know if there ... | public class ObjectAConfig { private int _valueB ; private string _valueA ; internal bool Consumed { get ; set ; } public int ValueB { get { return _valueB ; } set { if ( Consumed ) throw new InvalidOperationException ( ) ; _valueB = value ; } } public string ValueA { get { return _valueA ; } set { if ( Consumed ) thro... | Design a mutable class that after it 's consumed becomes immutable |
C# | Hello I am using MVC 5 and Entity Framework 6 for my project.I have a model like in the following diagram : And I need to query the entity product by starting from a set Of Tag objects.Please note that Tag object is an abstract class which actually is mapped by using the Table-Per-Entity strategy inheritance.this is th... | public IEnumerable < Product > SerachByTag ( IEnumerable < Tag > tagList ) ; [ { tagType : 1 , stringProperty : `` abc '' } , { tagType : 2 , intProperty : 9 } ] var p1 = ctx.Tags .OfType < FirstTagType > ( ) .Where ( x = > x.StringProperty.Equals ( `` abc '' ) ) .Select ( x = > x.Products ) ; var p2 = ctx.Tags .OfType... | Search by correlated entity |
C# | In [ this post ] , I 'm struggling to implement a State Pattern as @ jonp suggests . I do n't quite get how to use what 's he 's posted but it leads to the thought that maybe I 'm trying to fit a square peg into a round hole . So my question : If I have a visitor to my site that can play multiple roles i.e . a User cou... | class Vendor : User { } class Advertiser : User { } | Modelling `` I 'm a * but I 'm also a ** '' |
C# | I currently handle my exceptions like this : This works but it 's the same code I repeat many times . What I am looking for is some suggestion on how I could move this into an external function . I do n't necessarily need to move the try block there but at least the other code . Maybe a function that was passed the Exc... | try { } catch ( ServiceException ex ) { ModelState.Merge ( ex.Errors ) ; } catch ( Exception e ) { Trace.Write ( e ) ; ModelState.AddModelError ( `` '' , `` Database access error : `` + e.Message ) ; } | Can I move my exception code to a handling function . So I do n't have to repeat same code |
C# | Why is that var can only be declared and initialized in a single statement in C # ? I mean why we can not use : Since it is a implicit typed local variable `` var '' and the compiler takes the type that is right of the variable assignment operator , why would it matter that it should be only declared and initialized in... | var x ; x = 100 ; | Why is that var can only be declared and initialized in a single statement ? |
C# | With this : ... in a NavigatedTo ( ) event handler , Resharper tells me : `` Possible unintended reference comparison ; to get a value comparison , cast the left hand side to type 'string ' '' So should I change it to one of the following , and , if so , which one : | if ( args.Parameter == `` ContactIntermediaryPage '' ) if ( ( string ) args.Parameter == `` ContactIntermediaryPage '' ) if ( args.Parameter.ToString ( ) == `` ContactIntermediaryPage '' ) if ( args.Parameter.Equals ( `` ContactIntermediaryPage '' ) ) | What is the most appropriate way to compare a string to a stringable object by value ? |
C# | Am bit curious about the following behavior when attempting to round off Minutes/Seconds to nearest Hour ( in this case ignore the minute/second part ) .I tried two approaches , and benchmarked both with BenchMarkDotNet.Following were the results.I was curious why the New Operator is slower , if I were to assume , each... | private DateTime testData = DateTime.Now ; [ Benchmark ] public DateTime CeilingUsingNewOperator ( ) = > new DateTime ( testData.Year , testData.Month , testData.Day , testData.Hour + 1,0,0 ) ; [ Benchmark ] public DateTime CeilingUsingAddOperator ( ) = > testData.AddHours ( 1 ) .AddMinutes ( -testData.Minute ) .AddSec... | Benchmark DateTime |
C# | I 'm trying to work out the difference between the following : andI have found that the former causes an exception when used in a Where clause in Entity Framework Core 3.1 but the latter does not . I would have expected them to act similarly.Take the following example : public enum Fruit { Apple , Banana , Orange } It ... | someListOfEnums.Cast < int > ( ) someListOfEnums.Select ( a = > ( int ) a ) ? public class FruitTable { public int Id { get ; set ; } public Fruit Value { get ; set ; } } public class FruitContext : DbContext { public DbSet < FruitTable > Fruit { get ; set ; } } public void TestMethod ( FruitContext context ) { var lis... | Why am I seeing a difference between.Cast < int > ( ) and .Select ( a = > ( int ) a ) ? |
C# | Why is it comparing a single object and an IEnumerable valid for RefTypes ? | var fooRef = new FooRef ( ) ; var fooRefEnumerable = Enumerable.Empty < FooRef > ( ) ; var fooRefEquality = ( fooRef == fooRefEnumerable ) ; //This compiles without any errorsvar fooVal = new FooVal ( ) ; var fooValEnumerable = Enumerable.Empty < FooVal > ( ) ; //Compilation error : Error 1 Operator '== ' can not be ap... | Why comparing a single element against an IEnumerable is not a compilation error |
C# | Consider this code : Consider 2 threads are invoking DoSomething ( 2 ) . At the same time they will see that there 's no item with Key==2 in the dictionary . Consider Thread1 starts doing the expensive algorithm to retrieve the value of 2.Question 1 : Will Thread2 waits for Thread1 to accomplish its job ? Or simply tri... | void DoSomething ( int key ) { concurrentDictionary.GetOrAdd ( key , ( k ) = > { //Do some expensive over network and database to retrieve value . } ) ; | Does GetOrAdd wait if it 's busy on retrieving a value with same key ? |
C# | I am using this custom renderer : I read that with a TextCellRenderer it 's no longer necessary to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context . Can someone tell me if this is the case also for the ViewCellRenderer and if... | public class ExtViewCellRenderer : ViewCellRenderer { UITableViewCell _nativeCell ; public override UITableViewCell GetCell ( Cell item , UITableViewCell reusableCell , UITableView tv ) { _nativeCell = base.GetCell ( item , reusableCell , tv ) ; var formsCell = item as ExtViewCell ; if ( formsCell ! = null ) { formsCel... | Can I simplify this iOS renderer now that I no longer need to explicitly subscribe to property-changed-event |
C# | Suppose there is a method like this ( C # ) : If the sum does not fit into the int data type it is probably an error situation which is worth a unit test . Is Pex able to identify such errors and generate unit tests for those ? | public static int Add ( int x , int y ) { return x + y ; } | Can Pex automatically discover type overflow / underflow conditions ? |
C# | I have this piece of code : Problem : if test should be true , the code in the if statement does not get executed . I can not seem to debug this ( it just continues running my code ) .I think it may have to do something with deferred/immediate execution , but I ca n't find a solution ( I 've tried adding .ToList ( ) af... | DataTable dtDataTable = … ; var rows = dtDataTable.AsEnumerable ( ) ; var test = rows.Select ( x = > x [ `` id '' ] ) .Distinct ( ) .Count ( ) ! = rows.Count ( ) ; if ( test ) { MessageBox.Show ( `` test '' ) ; return false ; } | LINQ not executed correctly |
C# | What is an elegant way to pull out common formats ( e.g . datetime ) for string.format into accessible constants ? Ideally I would like to do something like the following , but I get the below error when I try to use this code . [ System.FormatException : Input string was not in a correct format . ] at Program.Main ( )... | var now = DateTime.Now ; var format = `` yyyy-MM-dd '' ; Console.WriteLine ( string.Format ( `` The date is { 1 : { 0 } } '' , format , now ) ) ; Console.WriteLine ( string.Format ( `` The date is { 1 : '' + format + `` } '' , format , now ) ) ; | DRY string formatting |
C# | Just wondering the best approach when it comes to async . At first my code looked like this ( example is simplified ) .But this approach is violating single responsibility and it might be confusing to other developers when they come try figure out what this code is doing . I was trying to find a way to chain together t... | public NotificationSummary SendNotification ( ) { var response = new NotificationSummary ( ) ; var first = FindSubscriptions ( 1 ) ; ... var seventh = FindSubscriptions ( 7 ) ; Task.WaitAll ( first , ... , seventh ) ; response.First = first.Result ; ... response.Seventh = seventh.Result ; return response ; } private Ta... | .Net Async ContinueWith VS Embedding Tasks in Task |
C# | I try to add a new `` Order '' to my Session . I begin create a session in my Global.aspx file under Session_Start : At my login page i make a new Session : Then at my shop page i want to add stuff to the session : At this last line i get att nullreference exception . Why could that be ? Here are my two classes : | Session.Add ( `` Cart '' , new WebShopData.Order ( ) ) ; Session [ `` userID '' ] = `` User '' ; ( ( Order ) Session [ `` Cart '' ] ) .UserID = userID ; if ( ( Order ) Session [ `` Cart '' ] ! = null ) ( ( Order ) Session [ `` Cart '' ] ) .OrderRow.Add ( new OrderRows ( { ArticleID = 2 , Quantity = 1 ) } ) ; public cla... | What is causing a nullreference exception in this code ? |
C# | This seems like something that I should have thought about before now , but it it n't . It also seems like there should be an existing way to do this.The problem : Say I have a class with a couple of constructorsAnd then elsewhere , I make a call to one of those constructors , but the second argument is null , it does ... | public class ModuleAction { public ModuleAction ( string url , string caption ) { ... } public ModuleAction ( string url , ModuleAction action ) { ... } } ModuleAction action = new ModuleAction ( `` http : //google.co.uk '' , null ) ; public class ModuleAction { public ModuleAction ( string url , string caption , bool ... | How to differentiate between overloads when an argument is null |
C# | I have a class with 3 members , only two of them relevant ; one is a Polygon and the other a int [ ] of coordinates . I want to be aware of that Polygon corresponding coordinates but I am really stuck here.By aware of the polygon coordinates I mean the abstract cubic coordinates I store in the class along that polygon ... | public class Tile { public int [ ] coords ; public Polygon hex ; public List < object > content ; } foreach ( int [ ] i in ValidCoordinates ) { int [ ] coords = i ; double apotema = Math.Sqrt ( Math.Pow ( 20 , 2 ) - Math.Pow ( 20 / 2 , 2 ) ) ; double auxX = x + ( coords [ 0 ] * ( 20 * 3 / 2 ) ) ; double auxY = y + ( co... | Get parent class of member in MouseEvent |
C# | So , after doing a ton of research on how to sandbox a c # script compiler so that the assemblies being loaded are only loaded into the sandbox AppDomain and not my primary AppDomain , I have run into the problem where all of the dll 's I created are unloaded upon unloading the sandbox AppDomain EXCEPT FOR ONE . That o... | return new Func < List < int > , int > ( ( list ) = > { var total = 0 ; foreach ( int i in list ) { total += i ; } return total ; } ) ; var provider = new CSharpCodeProvider ( new Dictionary < string , string > ( ) { { CompilerOptionName , CompilerOptionVersion } } ) ; var compilerParams = new CompilerParameters { Gene... | After Unloading AppDomain all assemblies are released EXCEPT ONE |
C# | I have two classes that I 'd like to keep in separate files.How do I ensure no other classes are allowed to call InformAddedToGrid ? I 'm trying to emulate Actionscript namespaces , which can be used on a method , in place of public , private , internal , etc . It does n't exactly protect the method , but forces an ext... | namespace GridSystem { public class Grid { public void AddItem ( GridItem item ) { item.InformAddedToGrid ( ) ; } } } namespace GridSystem { public class GridItem { public void InformAddedToGrid ( ) { Debug.Log ( `` I 've been added to the grid '' ) ; } } } | How do I ensure a Class can call a method on another Class , but not other Classes can call that method ? |
C# | You are designing an interface IFooLet 's say there are five implementations of this interface . Two of those implementations should also implement IDisposable as they use unmanaged resources . From a caller 's perspective , it would be easiest if IFoo implemented IDisposable so any IFoo can be wrapped in a using block... | public interface IFoo { void Bar ( ) ; } | Designing an interface where only some implementations require IDisposable |
C# | I have a method with a switch statement like this that gets called every time the size of the window gets changed : I now thought that there would be a more beautiful and shorter solution for this using a private method . However , here I 'm struggling . I could do something like this : I 'd just have to call this meth... | int fontSup = someBoolean ? 18 : 12 ; int fontSmall = someBoolean ? 22 : 15 ; int fontNormal = someBoolean ? 26 : 20 ; int fontTitle = someBoolean ? 28 : 22 ; switch ( Window.DeviceFamily ) { case DeviceFamily.Phone : fontSup = someBoolean ? 18 : 6 ; fontSmall = someBoolean ? 22 : 8 ; fontNormal = someBoolean ? 26 : 12... | Method to change font size with switch statement |
C# | I have a foreach which calls a method to get its collection.Visual studio does n't complain about this , nor does Resharper , however , before I continue to use this approach , I want to reach out and check if it is a recommended approach . | foreach ( var item in GetItemDetails ( item ) ) { } | Call a method in the declaration of a foreach |
C# | I want to populate a List of string arrays at compile timesomething like this : but I get a compile error : No overloaded method 'Add ' takes 2 argumentsWhy is this ? It works if they were n't string arrays with List < string > | List < string [ ] > synonyms = new List < string [ ] > { { `` enabled '' , `` enable '' , `` enabling '' } , { `` disabled '' , `` disable '' , `` disabling '' } , { `` s0 '' , `` s0 state '' } , { `` s5 '' , `` s5 state '' } } ; | Initializing a List with arrays |
C# | I found the following code in MSDN ( here ) which appears to be wrong ( compile-time error ) . Is n't it ? Consider this line : The class C is not derived from the class Test , so this assignment will not compile . Am I am missing something here ( some assumptions that I have not considered in the article ? ) Also the ... | delegate void D ( int x ) ; class C { public static void M1 ( int i ) { ... } public void M2 ( int i ) { ... } } class Test { static void Main ( ) { D cd1 = new D ( C.M1 ) ; // static method Test t = new C ( ) ; // < -- -- WRONG -- -- -- - D cd2 = new D ( t.M2 ) ; // instance method D cd3 = new D ( cd2 ) ; // another d... | Is it a Wrong Code in MSDN ? |
C# | `` using '' blocks are often written like this : rather than like this : In the first case , where no explicit reference to the new Foo object is set , is there any danger that the object could be disposed prior to the end of the block ? If not , why not ? | using ( new Foo ( ) ) { ... } using ( var f = new Foo ( ) ) { ... } | Do you need to set an explicit reference to a new 'd object in a using block ? |
C# | I 'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters . As I 'm not sure I 'm explaining this correctly , here 's what I 've got : ISvdPredictor uses ISvdModel : Now I want to implement another variation : Which uses IBiasSvdModel which derives f... | public interface ISvdPredictor { List < string > Users { get ; set ; } List < string > Artists { get ; set ; } float PredictRating ( ISvdModel model , string user , string artist ) ; float PredictRating ( ISvdModel model , int userIndex , int artistIndex ) ; } public interface ISvdModel { float [ , ] UserFeatures { get... | Inheritance problem in C # |
C# | This is within a .NET Core 1.1.4 project , so please take this into consideration.I 'm trying to create a function that would verify if a value can be assigned to a type , but I 'm encountering an issue with Nullable < T > types.My function : The if clause above handles the case if value is null , and attempts to verif... | protected void CheckIsAssignable ( Object value , Type destinationType ) { if ( value == null ) { // Nullable.GetUnderlyingType returns null for non-nullable types . if ( Nullable.GetUnderlyingType ( destinationType ) == null ) { var message = String.Format ( `` Property Type mismatch . Tried to assign null to type { 0... | Passing a ` Nullable < T > ` as a Type parameter to a C # function |
C# | Code searchView and PartialResultViewSearchViewSearch_PartiaViewPartial View ( AddEditGL ) I have View with Partial view ( is for results in table ) . When i click Edit button in Search_PartiaViewi need to open popup ( Partial View ( AddEditGL ) ) and data should be loaded ajax and submit the button after update.. I ne... | @ model Shared.Model.Search.GLSearch @ { ViewData [ `` Title '' ] = `` Search GL '' ; } < ! -- start page title -- > < div class= '' row '' > < div class= '' col-12 '' > < div class= '' page-title-box '' > < div class= '' page-title-right '' > < ol class= '' breadcrumb m-0 '' > < li class= '' breadcrumb-item '' > < a h... | Update the partia view based on Main view custom filters |
C# | I would like to do some similar process within a loop like this by calling a generic method with different types.AAA , BBB are all classes . CreateProcessor is a generic method in the class of MyProcessor.This does n't compile , I got the error saying Cannnot resolve symbol x.Technically , how to achieve it ? ( I know ... | new List < Type > { typeof ( AAA ) , typeof ( BBB ) } .ForEach ( x = > { var processor = MyProcessor.CreateProcessor < x > ( x.Name ) ; processor.process ( ) ; } ) ; | How to set the generic variable of the type Type in a loop ? |
C# | I 'm building custom control by extending ScrollableControl.Problem is that my custom control acts as container - I can drag controls into it : My question is how can I disable container functionality in class that extends ScrollableControlBelow are two test controls , one extends Control , second ScrollableControl | public class ControlBasedControl : Control { protected override Size DefaultSize { get { return new Size ( 100 , 100 ) ; } } protected override void OnPaint ( PaintEventArgs e ) { base.OnPaint ( e ) ; e.Graphics.FillRectangle ( Brushes.LightCoral , ClientRectangle ) ; } } public class ScrollableControlBasedControl : Sc... | UserControl extending ScrollableControl - disable container functinality |
C# | Building a bunch of reports , have to do the same thing over and over with different fields My Mind is drawing a blank on how i might be able to bring these two together . | public List < ReportSummary > ListProducer ( ) { return ( from p in Context.stdReports group p by new { p.txt_company , p.int_agencyId } into g select new ReportSummary { PKi = g.Key.int_agencyId , Name = g.Key.txt_company , Sum = g.Sum ( foo = > foo.lng_premium ) , Count = g.Count ( ) } ) .OrderBy ( q = > q.Name ) .To... | Is there any way to reduce duplication in these two linq queries |
C# | I wrote a custom comparer class.I have a test that fails when I new up two items and compare the hash codes . Why are the hashes different ? EDIT - Here is the complete class . I orginally used the example above for brevity but more information is neededThis implementation of GetHashCode also returns different hashes f... | public class ItemComparer : IEqualityComparer < Item > { public int GetHashCode ( Item x ) { return ( x == null ) ? 0 : new { x.Name , x.CompanyCode , x.ShipToDate , x.Address } .GetHashCode ( ) ; } [ TestMethod ] public void Two_New_Items_Have_The_Same_Hash_Code ( ) { // arrange var comparer = new ItemComparer ( ) ; I... | Why do two new objects not have the same hash code ? |
C# | Can someone please explain why these two methods are returning different values ? -The first method has 10 items in the list while the second has 1 . Why does the first ( Contains ( ) ) method never evaluate as true ? What I 'm trying to ask is why are 2 objects of the same type with the same values for each property n... | List < CustomerSummary > summaries = new List < CustomerSummary > ( ) ; for ( var i = 0 ; i < 10 ; i++ ) { var summary = new CustomerSummary ( ) { ID = 1 , Name = `` foo '' , balance = 50.00 } ; if ( ! summaries.Contains ( summary ) ) summaries.Add ( summary ) ; } List < CustomerSummary > summaries = new List < Custome... | C # contains behaviour |
C# | Looks like stupid question , but I just dont get it.My entity : In controller : Works as expected ( returns some element ) .But : Throws Sequence contains no elementsWhat do I miss ? | public class Page { public int Id { get ; set ; } // ... public int ? ParentId { get ; set ; } } db.Pages.First ( x = > x.ParentId == null ) ; int ? test = null ; db.Pages.First ( x = > x.ParentId == test ) ; | Linq expression with nullable |
C# | I have an Access 97 database that I am trying to get the data schema and the data out of . I do n't know how many tables there are , or what they 're called , nor what column names there are.I have no problem getting into the database programmatically , but how do you discover the schema ? I 'm using this to get the sc... | static DataTable GetSchemaTable ( string connectionString ) { using ( OleDbConnection connection = new OleDbConnection ( connectionString ) ) { connection.Open ( ) ; DataTable schemaTable = connection.GetOleDbSchemaTable ( OleDbSchemaGuid.Tables , new object [ ] { null , null , null , `` TABLE '' } ) ; return schemaTab... | Get tables/schema from access 97 database |
C# | Possible Duplicate : C # : Is operator for Generic Types with inheritance Is it possible to add a list into another list whilst changing class type from Deal to DealBookmarkWrapper without using the foreach statement ? Thanks . | var list = new List < IBookmarkWrapper > ( ) ; foreach ( var deal in deals ) { list.Add ( new DealBookmarkWrapper ( deal ) ) ; } | Is it possible to recreate this statement without using a foreach ? |
C# | I am trying to solve copy pasting a column with values from excel into a textarea in my web app.The user will simply select row values in a column , e.g . the excel table looks like ( the user will not select the header ) When I paste this into a text area , it pastes in with the spaces , e.g.But when I post this text ... | -- -- -|Code | -- -- -| 1 | -- -- -| 2 | -- -- -| 3 | -- -- -| 4 | -- -- -| 5 | -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- |1 ||2 ||3 ||4 ||5 || | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public ActionResult Search ( string searchTerms ) { // ` searchTerms ` = `` ... | Separating excel multiple row selection |
C# | I 'm creating an attribute which accepts up to 4 arguments.I 've coded this way : I need to use it like this : Is there any way to code in only one constructor the 4 constructors above to avoid repetition ? I 'm thinking in something like JavaScript 's spread operator ( ... args ) = > args.forEach ( arg = > setMethod (... | internal class BaseAnnotations { public const string GET = `` GET '' ; public const string POST = `` POST '' ; public const string PATCH = `` PATCH '' ; public const string DELETE = `` DELETE '' ; public class OnlyAttribute : Attribute { public bool _GET = false ; public bool _POST = false ; public bool _PATCH = false ... | How to create a constructor which accepts up to 4 arguments ? |
C# | Given the following code snippet : If I remove the `` System . '' from in front of Int32 in my declaration for the `` Foo '' type alias , I get a compiler error . Despite the fact that I 'm using the System namespace at the top of the file , the compiler ca n't find an unqualified `` Int32 '' type.Why is that ? | using System ; using Foo = System.Int32 ; namespace ConsoleApplication3 { class Program { static void Main ( string [ ] args ) { } } } | Why do types referenced outside of a namespace need to be fully qualified ? |
C# | I have implemented a basic ( naive ? ) LINQ provider that works ok for my purposes , but there 's a number of quirks I 'd like to address , but I 'm not sure how . For example : My IQueryProvider implementation had a CreateQuery < TResult > implementation looking like this : Obviously this chokes when the Expression is... | // performing projection with Linq-to-Objects , since Linq-to-Sage wo n't handle this : var vendorCodes = context.Vendors.ToList ( ) .Select ( e = > e.Key ) ; public IQueryable < TResult > CreateQuery < TResult > ( Expression expression ) { return ( IQueryable < TResult > ) Activator .CreateInstance ( typeof ( ViewSet ... | How to make LINQ-to-Objects handle projections ? |
C# | In C # , I can create an instance of every custom class that I write , and pass values for its members , like this : This way of creating objects is called object creation expressions . Is there a way I can do the same in Java ? I want to pass values for arbitrary public members of a class . | public class MyClass { public int number ; public string text ; } var newInstance = new MyClass { number = 1 , text = `` some text '' } ; | Are there object creation expressions in Java , similar to the ones in C # ? |
C# | I have the following function that checks a string and keeps only the letters and digits . All other characters are removed . However I want one character only `` - '' to escape this function and not to be removed . For instance I want Jean-Paul to stay as it with the `` - '' in between the two names . How can I do tha... | String NameTextboxString = NameTextbox.Text ; NameTextboxString = new string ( ( from c in NameTextboxString where char.IsLetterOrDigit ( c ) select c ) .ToArray ) ; nameLabel.Text = NameTextboxString ; | I want one character to escape IsLetterOrDigit |
C# | I need to take a Widget that already has several property values set . I need to change the Widget 's name . I 'm drawn toward Option 3 , but I 'm having a hard time articulating why.I 'd like to play Devil 's Advocate with a few questions and gather responses , to help me explain why I 'm drawn to Option 3.Option 1 : ... | public void Do ( Widget widget ) { // 1 widget.Name = `` new name '' ; } public void Do ( ref Widget widget ) { // 2 widget.Name = `` new name '' ; } public Widget Do ( Widget widget ) { // 3 widget.Name = `` new name '' ; return widget ; } | How best to modify and return a C # argument ? |
C# | I had some problems with using the authorization before so I got a brand new everything - new computer , new OS , fresh installation of VS , new app and DB in a new resource group on the Azure . The whole shabang.I can confirm that I can log in to the Azure DB as the screenshots below show.I can see the databases , tab... | Server=tcp : f8goq0bvq7.database.windows.net,1433 ; Database=Squicker ; User ID=Chamster @ f8goq0bvq7 ; Password=Abc123 ( ) ; Encrypt=True ; TrustServerCertificate=False ; Connection Timeout=10 ; | Ca n't store users in the default MVC application |
C# | I am trying to understand the way inheritance works in C # . Basically , I have a base class Base that has a simple function sayIt . The function makes use of a property `` i '' that is redefined in subclasses . Here , it is redefined as 1 from 0 . When I run this program , I get `` 0 '' as output rather than `` 1 '' w... | class Program { static void Main ( string [ ] args ) { Derived d = new Derived ( ) ; Console.WriteLine ( d.sayIt ( ) ) ; Console.ReadLine ( ) ; } } class Base { int _i = 0 ; public int i { get { return _i ; } } public String sayIt ( ) { return Convert.ToString ( this.i ) ; } } class Derived : Base { int _i = 1 ; public... | Inheritance misunderstanding in C # |
C# | From the Kotlin documentation page : In the code snippet above , I understand everything except that Class < T > thing . I assume it is the C # equivalent of the following : And the client code would say something like : But I ca n't be sure because that whole System.Type parameter seems redundant in the face of the ge... | // public final class Gson { // ... // public < T > T fromJson ( JsonElement json , // Class < T > classOfT ) // throws JsonSyntaxException { // ... public sealed class Gson { public T FromJson < T > ( JsonElement json , System.Type Type ) { } } var gson = new Gson ( ) ; var customer = gson.FromJson < Customer > ( json... | Could you please explain this piece of code in terms of C # code ? |
C# | I have an asp.net webforms application . Every single aspx.cs class needs to inherit from BasePage.cs which inherits from System.Web.UI.Page.Desired Page Inheritance : How do I force that when a new child page is created it inherits from BasePage.cs and not System.Web.UI.Page ? Potential solutions : Is there a way to c... | class MyChildPage : BasePage : System.Web.UI.Page | How to throw Exception when class has wrong inheritance |
C# | I am trying to create a method using LINQ that would take X ammount of products fron the DB , so I am using the .TAKE method for that.The thing is , in situations I need to take all the products , so is there a wildcard I can give to .TAKE or some other method that would bring me all the products in the DB ? Also , wha... | var ratingsToPick = context.RatingAndProducts .ToList ( ) .OrderByDescending ( c = > c.WeightedRating ) .Take ( pAmmount ) ; | Is there a wildcard for the .Take method in LINQ ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.