lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | Problem : I have a web api which expose a method UploadFile , which will upload a file from a client to a specific directory of the server . The piece of code that handle the request and do the upload is the following : I always calledthis method using the following statement : where UploadFileAsync ( which is on the c... | var boundary = MultipartRequestHelper.GetBoundary ( MediaTypeHeaderValue.Parse ( Request.ContentType ) , _defaultFormOptions.MultipartBoundaryLengthLimit ) ; var reader = new MultipartReader ( boundary , HttpContext.Request.Body ) ; try { // Read the form data . var section = await reader.ReadNextSectionAsync ( ) ; // ... | How to handle properly temporary files ? |
C# | Suppose I have a struct type implementing IDisposible , and if I use the codes below : Of course I see after the block of using , the ms is disposed . However what about the struct in `` InnerAction '' ? Is it still alive because of deep copy or it is also disposed ? If it 's still alive ( not disposed ) , Must I use `... | using ( MyStruct ms = new MyStruct ( ) ) { InnerAction ( ms ) ; //Notice `` InnerAction '' is `` InnerAction ( MyStruct ms ) '' } | Is the deep copy of struct type also disposed when in the block of “ Using…… ” ? |
C# | I have two list of date . I have to compare both list and find missing date.My first list looks like this : My second list looks like this I have to find the missing date between the two list : I tried this But it did n't work . Can anyone help me with this ? | 2015-07-212015-07-222015-07-232015-07-242015-07-252015-07-262015-07-27 2015-07-212015-07-222015-07-232015-07-252015-07-262015-07-27 var anyOfthem = firstList.Except ( secondList ) ; | How to compare to list of date in C # ? |
C# | Im still new to C # and was wondering how one would have multiple things happen when an if condition is met . for example.When I do something like this it dosnt complete all the desired results.P.S If this isnt the right site to go for newbie questions like this does anyone know where I can go ? ( after research of cou... | int number = ( Convert.ToInt32 ( textbox1.text ) ) ; if ( number == 1 ) textbox2.Text = `` 1 '' ; number2 = 33 ; textbox3.text = ( Convert.ToString ( number2 ) ) ; | 'if ' statements |
C# | Long story short , if I do this : Will something ever be null ? I read the msdn and it does n't specify the GetName ( ) and Version parts . | string myV = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Version.ToString ( ) ; | Can an assembly have no version ? |
C# | During a recent code review a colleague suggested that , for class with 4 int properties , assigning each to zero in the constructor would result in a performance penalty . For example , His point was that this is redundant as they will be set to zero by default and you are introducing overhead by essentially performin... | public Example ( ) { this.major = 0 ; this.minor = 0 ; this.revision = 0 ; this.build = 0 ; } | Assigning integers fields/properties to zero in a constructor |
C# | To generate the needed tokens - consumer key , consumer secret , token ID , token secret - we are creating an integration , and access tokens , and assigning them to an employee with a specific role that has access to TBA . ( Refer to https : //medium.com/ @ morrisdev/netsuite-token-based-authentication-tba-342c7df5638... | private static void GetEmployees ( ) { EmployeeSearch search = new EmployeeSearch ( ) ; EmployeeSearchBasic esb = new EmployeeSearchBasic ( ) ; esb.isInactive = new SearchBooleanField ( ) ; esb.isInactive.searchValue = false ; esb.isInactive.searchValueSpecified = true ; search.basic = esb ; SearchResult res = Client.S... | Is it possible to find the role of a netsuite employee using TBA as authentication method ? |
C# | I have 2 hash sets like this.I am using C # I want to compare those two sets and want to get the output like | Hash_1 = { 1 , 2 , 3 , 4 , 5 } Hash_2 = { 4 , 5 , 6 , 7 , 8 } Hash_3 = { 1 , 2 , 3 , 6 , 7 , 8 } | I want to compare 2 hash sets and take out the differences |
C# | Looking at this code : Let 's say that a , b , c , d also have nested async awaits ( and so on ) Async/await POV - for each await , there is a state machine being kept.Question ( theoretical ) : As each state machine is kept in memory , could this cause big memory consumption ? It might be a vague question to ask , but... | public async Task < T > ConsumeAsync ( ) { await a ( ) ; await b ( ) ; await c ( ) ; await d ( ) ; //.. } | Can a long async-await chain cause big memory consumption ? ( theoretically ) |
C# | Why does : sCanBeNull equate to false ? I 'm writing a code generator and need to ensure every type passed to it is nullable , if it is n't already . Do I need to have to explicitly check for a string or am I missing something ? | string s = `` '' ; bool sCanBeNull = ( s is Nullable ) ; s = null ; //Get the underlying type : var type = field.FieldValueType ; //Now make sure type is nullable : if ( type.IsValueType ) { var nullableType = typeof ( Nullable < > ) .MakeGenericType ( type ) ; return nullableType.FullName ; } else { return type.FullNa... | String is Nullable returns false |
C# | I wrote a custom action method selector attribute that has three bool properties . It 's invalid for all three of them to be false . At least one of them has to be true . When IsValidForRequest gets executed I check that at least one of them is true . But if none is , which exception should I throw ? Some relevant code... | public class MyCustomAttribute : ActionMethodSelectorAttribute { public bool Prop1 { get ; set ; } public bool Prop2 { get ; set ; } public bool Prop3 { get ; set ; } public MyCustomAttribute ( ) { this.Prop1 = true ; this.Prop2 = true ; this.Prop3 = true ; } public override bool IsValidForRequest ( ControllerContext c... | Which exception should be thrown ? |
C# | I 've been hitting my head with this for the past few hours , so here goes . Maybe it 's a common mistake for someone with little experience with multi-threading ? Who knows.In the included code I instantiate 3 threads that run method DisplayValues ( DateTime Now , int Period ) . The debugger stops three times in each ... | bool thread0Running = false ; bool thread1Running = false ; bool thread2Running = false ; DateTime DateNow = new DateTime ( 2014 , 5 , 8 , 4 , 0 , 0 ) ; while ( ( ! thread0Running || ! thread1Running || ! thread2Running ) & & DateNow.Hour == 4 ) { if ( ( DateNow.Hour == TaskDateTime.Hour ) & & ( DateNow.Minute == 20 ) ... | Consequence of running multiple concurrent threads ? |
C# | I have a class that needs to call a method NotifyPropertyChanged when any of its properties are changed . What I 've seen in examples is something like : Is this really the idiomatic way to do it ? It requires several lines of boilerplate for every property I want to add . Moreover , if I want to change the name of the... | private string property1_ ; public string Property1 { get { return property1_ ; } set { property1_ = value ; NotifyPropertyChanged ( ) ; } } private string property2_ ; public string Property2 { get { return property2_ ; } set { property2_ = value ; NotifyPropertyChanged ( ) ; } } // ... ... . | Redundant code in getters and setters |
C# | When the property have some collection type likeIMHO , it 's better to return empty collection instead of null value . There are many ways to implement such functionality.This way allow to decrease number of class fields , but you need to put code in each constructor.This is standard way . But when somebody write somet... | public IList < MyItemClass > MyList { get ; } public IList < MyItemClass > MyList { get ; private set ; } public MyClass ( ) { MyList = new List < MyItemClass > ( ) ; } private List < MyItemClass > _myList = new List < MyItemClass > ( ) ; public IList < MyItemClass > MyList { get { return _myList ; } } private List < M... | Properties of collection type |
C# | I have a class ( Class B ) that inherits another class ( Class A ) that contains virtual methods.Mistakenly , I omitted the override keyword when declaring a ( supposed to be ) overriding method in Class B.Class AClass BThe code compiled without a problem . Can anyone explain why ? | public class ClassA { public virtual void TestMethod ( ) { } } public class ClassB : ClassA { public void TestMethod ( ) { } } | Why does this C # code compile fine when there is an ambiguous virtual method ? |
C# | When I try to call Foo.Calc ( `` Foo '' ) ; I have exception `` Object reference not set to an instance of an object . `` because static constructor of Foo was not called and CalcFunction is null . I do n't want to use Init method for Foo class and call it before calling Calc ( ) .Can I change order of calling construc... | class Program { static void Main ( string [ ] args ) { Foo.Calc ( `` Foo '' ) ; } } public abstract class Base { protected static Func < string , int > CalcFunction ; public static void Calc ( string str ) { Console.WriteLine ( CalcFunction ( str ) ) ; } } public class Foo : Base { static Foo ( ) { CalcFunction = s = >... | Order of calling constructors |
C# | I 'm relatively new to OOP , so wanted to clear a few things , I have the following piece of codeOutput : My questions are as follows :1 ) Why is the base class constructor called when I instantiate objects with the ChildClass constructor ? without explicitly specifying the base keyword . Is there any way to avoid call... | class Parent { public Parent ( ) { Console.WriteLine ( `` Parent Class constructor '' ) ; } public void Print ( ) { Console.WriteLine ( `` Parent- > Print ( ) '' ) ; } } class Child : Parent { public Child ( ) { Console.WriteLine ( `` Child class constructor '' ) ; } public static void Main ( ) { Child ChildObject = ne... | Inheritance doubts |
C# | I have an issue with my COM add-in that has been dragging for months , and I ca n't figure out why.The IDTExtensibility2 implementation has been peer reviewed by Carlos Quintero ( the guy behind MZ-Tools ) already , and deemed correct.Per his recommendations the OnBeginShutdown implementation sets a flag that 's checke... | public void OnBeginShutdown ( ref Array custom ) { _isBeginShutdownExecuted = true ; ShutdownAddIn ( ) ; } private void ShutdownAddIn ( ) { if ( _kernel ! = null ) { _kernel.Dispose ( ) ; _kernel = null ; } _ide.Release ( ) ; _isInitialized = false ; } public void HandleEvents ( ) { // register the unmanaged click even... | Cleaning up CommandBar buttons |
C# | When I use setall in program : but if i use set for every element of bitarrayWhy different result in two program when use set result is -1 and when use setall in second program result is 255 ? | BitArray bb = new BitArray ( 8 ) ; bb.SetAll ( true ) ; int [ ] dd = new int [ 1 ] ; bb.CopyTo ( dd , 0 ) ; for ( int i = 0 ; i < dd.Length ; i++ ) Console.WriteLine ( dd [ i ] ) ; // result is -1 BitArray bb = new BitArray ( 8 ) ; bb.Set ( 0 , true ) ; bb.Set ( 1 , true ) ; bb.Set ( 2 , true ) ; bb.Set ( 3 , true ) ; ... | Difference between set and set all in c # |
C# | Why is n't this allowed ? When I try to compile , I get : CS0826 : No best type found for implicitly-typed arrayFeels a bit counter-intuitive , because with a regular anonymous type I can do this : | int A = 5 , B = 10 , X = 5 , Y = 5 ; var array = new [ ] { new { A , B } , new { X , Y } } ; int X = 5 , Y = 5 ; var point = new { X , Y } ; | Why are implicit property names not allowed in an array of anonymous types ? |
C# | I have an extension method to remove certain characters from a string ( a phone number ) which is performing much slower than I think it should vs chained Replace calls . The weird bit , is that in a loop it overtakes the Replace thing if the loop runs for around 3000 iterations , and after that it 's faster . Lower th... | int testNums = 5_000_000 ; Console.WriteLine ( `` Building `` + testNums + `` tests '' ) ; Random rand = new Random ( ) ; string [ ] tests = new string [ testNums ] ; char [ ] letters = { ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , '+ ' , '- ' , ' ( ' , ' ) ' } ; for ( int t = 0 ; t ... | C # Extension method slower than chained Replace unless in tight loop . Why ? |
C# | I 'm trying to create a list of ViewModels out of a DTO by calling a select on the list of DTO's.However , the compiler gives me an error saying : The type arguments for method can not be inferred from the usage try specifying the type argumentsMy question is , why ca n't it ? Both TextSectionDTO and ImageSectionDTO ar... | private List < Section > BuildSectionViewModel ( IEnumerable < SectionDTO > ss ) { var viewModels = ss.Select ( ( SectionDTO s ) = > { switch ( s.SectionType ) { case Enums.SectionTypes.OnlyText : return new TextSection ( ( TextSectionDTO ) s ) ; case Enums.SectionTypes.OnlyImage : return new ImageSection ( ( ImageSect... | Why ca n't the compiler infer the type for this select call ? |
C# | I am trying to build the version 4.3.0 release . But I am getting the known error : Could not load file or assembly 'DotNetOpenAuth.Core ' or one of its dependencies . Strong name signature could not be verified . The assembly may have been tampered with , or it was delay signed but not fully signed with the correct pr... | MessageDictionary dictionary = this.Channel.MessageDescriptions.GetAccessor ( signedMessage ) ; MessageDictionary dictionary = this.Channel.MessageDescriptions.GetAccessor ( signedMessage , true ) ; | Compiling specific version of DotNetOpenAuth with a small change , signing issues |
C# | I have a lot of pieces of code which has to be run one time during initialization.I have to use a boolean flag this way because it is in an event Because it happens often , I did something to make this boolean variable to look like a fuse : So I did this : If it is initialized to false , the result of the query returns... | bool _fuse ; void PerformLayout ( ) { Size size ; if ( ! _fuse ) { size = _InitialContainerSize ; _fuse = true ; } else size = parent.Size ; // ... } bool _fuse ; void PerformLayout ( ) { Size size ; if ( ! Burnt ( ref _fuse ) ) size = _InitialContainerSize ; else size = parent.Size ; // ... } public static bool Burnt ... | Doing a fuse with a boolean |
C# | I know that is good practice use LINQ instead of iterative loops , can I modify this code to use LINQ ? Thanks.Update : can the call to filterStudyPriors ( ) method can be part of the LINQ ? | List < string > priorsLstIDs = ServiceUtil.extractColumnValuesAsStringVals ( tqrPriors , Helper.STUDY_ID ) ; List < DateTime > priorsLstDates = ServiceUtil.extractColumnValuesAsDateTimeVals ( tqrPriors , `` STUDY_DATE '' ) ; List < PriorElemSt > priorsElemLst = new List < PriorElemSt > ( priorsLstIDs.Count ) ; PriorEle... | How can I switch that code to use LINQ |
C# | I have a ( probably ) dumb question about display formatting of nullable types . At the moment , when I need to indicate that a field of a nullable type does indeed have a null value , I code it like this : Or some variation of that basic text . I do n't think I can use a coalesce operator - or at least I do n't think ... | var stringToDisplay = nullableDecimal.HasValue ? nullableDecimal.ToString ( ) : `` N/A '' ; | A more elegant way to display null ? |
C# | I am using helper methods to pre-filter all of my queries based upon user access permissions . Assuming a method signature of : Why does this work when using LINQ : But not this : I am OK doing the first one , but having been away from LINQ for a few years , it would be nice to understand the why on this one.By not wor... | public IQueryable < Client > GetAllClients ( ) IQueryable < Client > allItems = GetAllClients ( ) ; return ( from item in allItemswhere item.Name.Equals ( name , StringComparison.InvariantCultureIgnoreCase ) select item ) .FirstOrDefault ( ) ; return ( from item in GetAllClients ( ) where item.Name.Equals ( name , Stri... | Why one query works and not the other ? |
C# | I have a class : Method Check is called from multiple threads quite often . Method Update is called from a single thread which monitors some source ( database , http service etc. ) . Is this pattern of Volatile.Read / Volatile.Write usage correct ? | public class Checker { private HashSet < int > _hs = new HashSet < int > ( ) ; public bool Check ( int a ) { return Volatile.Read ( ref _hs ) .Contains ( a ) ; } public void Update ( IEnumerable < int > items ) { Volatile.Write ( ref _hs , new HashSet < int > ( items ) ) ; } } | C # : volatile reads and writes of HashSet |
C# | We 're writing an SDK for a CAD program and have run into a slight disagreement regarding a specific type of function ( not just disagreement between different people , also disagreement between my two brain-halves ) .Imagine there 's a lot of classes for specific curve types ( ellipse , circle , arc , line , bezier et... | public NurbsCurve Circle.ToNurbsCurve ( ) { // Return a circular NurbsCurve or null if the Circle is invalid . } public static NurbsCurve NurbsCurve.CreateFromCircle ( Circle ) { // Return a circular NurbsCurve or null if the Circle is invalid . } | .Net SDK problem , which way to go ? |
C# | I thought I had it set up correctly ; however , I receive an error of System.FormatException : 'Input string was not in a correct format . on the line WriteLine ( `` The area of your circle is : `` + circleArea ( Double.Parse ( ReadLine ( ) ) ) .ToString ( ) ) ; when no value is entered . I would like it to have a defa... | class Program { static void Main ( string [ ] args ) { WriteLine ( `` What is the radius of your circle : `` ) ; WriteLine ( `` The area of your circle is : `` + circleArea ( Double.Parse ( ReadLine ( ) ) ) .ToString ( ) ) ; ReadKey ( ) ; } static double circleArea ( double radius = 5.00 ) { return Math.PI * ( radius *... | C # Pass an integer variable with an optional default value |
C# | Using C # 8 , Visual Studio 2019 16.7.2 , given the following C # code : Intellisense hovering over theString shows a tooltip of local variable ( string ? ) theStringMy GetStringAsync method never returns a nullable string , yet the variable is inferred as being nullable.Is this an intellisense bug ? Or is there someth... | # nullable enablepublic async Task < string > GetStringAsync ( ) ; ... public async void Main ( ) { var theString = await GetStringAsync ( ) ; ... } | Why does async/await in C # return nullable values even when told not to ? |
C# | I 've reduced my question to an example involving animals . I want to define a set of interfaces ( /abstract classes ) that allow anyone to create a factory for a given animal and register it with a central registrar : AnimalRegistry keeps track of all the registered AnimalFactory objects , which in turn produces and p... | AnimalRegistry registry = new AnimalRegistry ( ) ; registry.Register < ElephantFactory > ( ) ; registry.Register < GiraffeFactory > ( ) ; Animal a1 = registry.GetInstance < ElephantFactory > ( ) .Create ( new ElephantParams ( weight : 1500 ) ) ; Animal a2 = registry.GetInstance < GiraffeFactory > ( ) .Create ( new Gira... | Using generics with extensible factories ? |
C# | The methods of this classcompile into this IL code : So far , so good . But neither ceq nor System.Object : :Equals ( object , object ) take a possibly overridden op_Equality or Object.Equals into account.Why is that ? Why do none of the three proposed ways call operator== or an overridden Equals method ? Should n't Sy... | public class NullTester { public bool EqualsNull < T > ( T o ) where T : class { return o == null ; } public bool IsNull < T > ( T o ) where T : class { return o is null ; } public bool EqualsCall < T > ( T o ) where T : class { return object.Equals ( o , null ) ; } } .method public hidebysig instance bool EqualsNull <... | Overriden equality operator is never called |
C# | I 'm very new to MVC and I 'm trying to figure out if there is a better way to do this . I have a textbox for the user to put in their search , then based on that search I am displaying some results below said search box . I am trying to avoid having so much code logic in my view and would like to know if there is a be... | @ section CustomerPrefixInfo { @ if ( Model.Results == PrefixSearch.SearchResults.CustomerFound ) { @ Html.Partial ( `` _CustomerPrefixInfo '' ) } @ if ( Model.Results == PrefixSearch.SearchResults.PrefixResultsFound ) { @ Html.Partial ( `` _PrefixResults '' ) } @ if ( Model.Results == PrefixSearch.SearchResults.Animal... | MVC Partial Views issue |
C# | Based on a proposed answer to my other question here ... is it possible to update a variable during LINQ enumeration so you can use it as part of a test ? For instance , is anything like this possible ? This would make the search inclusive of limitItem . | // Assume limitItem is of type Foo and sourceList is of type List < Foo > // Note the faux attempt to set limitItemFound in the TakeWhile clause// That is what I 'm wondering.sourceList.Reverse ( ) .TakeWhile ( o = > ( o ! = limitItem ) & & ! limitItemFound ; limitItemFound = limitItemFound || ( o == limitItem ) ) .Fir... | Can you set/update a value in real-time within a LINQ statement during iteration ? |
C# | I 'm trying to understand ConfigurationManager in .NET by practicing it in different scenarios.I have two projects : Project1 and Project2.Project2 uses Project1.My Situation : I have a section ( serializedfilename ) in my app.config file in project1.and I have this line of code in a class1 of project1In project2 , I c... | private static string SerializedConfiguration = ConfigurationManager.AppSettings [ `` SerializedFilename '' ] ; | On Understanding ConfigurationManager in .NET |
C# | I am learning C # and came across the keyword module . I would like to know what this module keyword in C # is and how it is useful . For example , consider the below code : | [ module : Test ] public class TestAttribute : Attribute { } | What is the `` module '' keyword in C # .NET ? |
C# | So , I 've got this function which reads from an INI file : Now , when I step through , and get to the last Log ( ) in the function , and I hover over RigInfo , Visual Studio intellisense shows me RigInfo { string [ 30 ] } . Now , I 've always understood that = new string [ 9 ] would create a 9 element array . So why i... | private void GetRigInfo ( ) { RigInfo = new string [ 9 ] ; var fileLocation = new string [ 2 ] ; // The problem is that there 's no telling where the hddrigsite.ini will be stored . So , we have to find out where it is from the hddconfig.ini . Log ( `` Locating rig info '' ) ; // There 's no telling if this will be on ... | Why does the array have more elements than I 've defined ? |
C# | I found Boolean source code on http : //referencesource.microsoft.com/ # mscorlib/system/boolean.cs : why does it not throw a StackOverflowException ? | public struct Boolean { ... private bool m_value ; ... } | Why does Boolean not throw a StackOverflowException ? |
C# | There is this problem which I need to solve in my program which is about the get/set function.HERE IS THE FULL UNEDITED CODE : https : //pastebin.com/Vd8zC51mEDIT : My good friend found the solution , which was to use `` value '' like so : I 'M SORRY IF I WASTED ANYONES TIME ... ! The problem goes like this : Make a Pr... | { get { return this.returnValue ; } set { if ( value > 30 ) { this.returnValue = value - ( value * 0.10f ) ; } else { this.returnValue = value ; } } } public class Book { public string Name ; public string writerName ; public string bPublisher ; public float bPrice ; public string bTheme ; public float returnValue ; pu... | Am I using the set/get function wrong ? |
C# | So out of curiosity and idle boredom , I was fooling around with benchmarking Shlemiel the painter 's algorithm . I started with a blank string , created another one of 1000 blank spaces , and started adding one to the other , using plain old inefficient string concatenation , timing how long it took each time.As expec... | string s1 = `` '' ; string s2 = `` '' ; while ( s2.Length < 1000 ) { s2 += `` `` ; } while ( true ) { Stopwatch sw = Stopwatch.StartNew ( ) ; s1 += s2 ; sw.Stop ( ) ; Console.WriteLine ( `` { 0 } | { 1 } '' , s1.Length , sw.ElapsedMilliseconds ) ; } Length | Time ( ms ) -- -- -- -- -- -- -- -- -- -- -- - 32250000 | 117... | What 's causing this spike in time of string concatenation ? |
C# | I would like to check if an entity is already added to the database . So , how can I see this difference between a and b ? To make it clearer , if I have this : How can I see if thing needs to be inserted ? | var a = dataContext.Things.First ( x = > x.Name == something ) ; var b = new Thing { Name = something } ; var thing = dataContext.Things.FirstOrDefault ( x = > x.Name == something ) ? ? new Thing { Name = something } ; | C # : How to see if a Linq2SQL entity is in the database |
C# | Basic c # question . In the sample bellow But the 'is ' does n't like the type variable . Any ideas there should be a simple answer . | List < object > list = new List < object > ( ) ; list.Add ( `` one '' ) ; list.Add ( 2 ) ; list.Add ( ' 3 ' ) ; Type desiredType = typeof ( System.Int32 ) ; if ( list.Any ( w = > w is desiredType ) ) { //do something } | C # Is Type in list question |
C# | I have a function that is like the followingThat double nesting just feels wrong to me . Is there a better way to implement this pattern ? Thank you everyone for helping , I end up going with the trinary route . It helped turn this : in to this | string Foo ( bool A , bool B ) { if ( A ) { if ( B ) { return `` W '' ; } else { return `` X '' ; } } else { if ( B ) { return `` Y '' ; } else { return `` Z '' ; } } } if ( female ) { if ( nutered ) { destRow [ `` TargetSex '' ] = `` FS '' ; } else { destRow [ `` TargetSex '' ] = `` F '' ; } } else { if ( nutered ) { ... | Simplifing a nested IF statement |
C# | What is common rule to check if IEnumerable < T1 > covariant to IEnumerable < T2 > ? I 've made some experiments:1.Works because IEnumerable < out T > is covariant and String inherits Object . 2.MyStruct is actually an Object , but it does not work because Object is reference type and MyStruct is value type . OK , I se... | Object Obj = `` Test string '' ; IEnumerable < Object > Objs = new String [ 100 ] ; interface MyInterface { } struct MyStruct : MyInterface { } ... ..Object V = new MyStruct ( ) ; Console.WriteLine ( new MyStruct ( ) is Object ) ; // Output : True . IEnumerable < Object > Vs = new MyStruct [ 100 ] ; // Compilation erro... | How to check if ` IEnumerable < T1 > ` covariant to ` IEnumerable < T2 > ` ? |
C# | I have a method which takes an interface type and evaluates what the type is and from that I need to return a type related to it . But I 'm not sure how to make the type returns flexible for it . I tried something like this : But I get this error : Can not implicitly convert type Hex to TAm I on the right lines here us... | public static T GridPosition < T > ( IReSizeableGrid gridData ) { if ( gridData is Hex ) { var hexGrid = ( HexGrid ) gridData ; return HexLibrary.WorldToHex ( WorldPoint ( Input.mousePosition , GroundPlane ) , hexGrid ) ; } if ( gridData is QuadGrid ) { var quadGrid = ( QuadGrid ) gridData ; return Grid.Get ( WorldPoin... | Custom return type based on input data |
C# | For the life of me , I can not figure out why this line of code : throws an ArgumentOutOfRangeException under Roslyn CTP3 . | var literalExpressionSyntax = Syntax.LiteralExpression ( SyntaxKind.CharacterLiteralExpression ) ; | LiteralExpression - ArgumentOutOfRangeException |
C# | I compiled the following code in .Net 3.5 , Visual Studio 2012 . I expected to get an error on the line when the array gets assigned to my IReadOnlyCollection , because there is no implicit conversion defined from Array to my Interface.It compiles successful and does also not create any runtime errors.Notes to be aware... | using System ; using System.Collections ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace System.Collections.Generic { public interface IReadOnlyCollection < T > : IEnumerable < T > , IEnumerable { int Count { get ; } } } using System.Collections.Generic ; namespace ConsoleApplicati... | Why is the following Code Compiling and Executing successfully ? |
C# | My task is simple : I have to create a dynamic array ( which means that its size can change during all runtime ) and fill it ( depends on user input , also in runtime ) with objects of different types . Moreover , it should be possible for me to access fields ( and/or methods ) of every object in the array . Obviously ... | public class Point { } public class RightTriangle : Point { public double sideA , sideB ; } public class Circle : Point { public double radius ; } public class Cone : Circle { public double radius , height ; } RightTriangle rt1 = new RightTriangle ( ) ; Cone cn1 = new Cone ( ) ; List < Point > objs = new List < Point >... | Calling item methods on an array of different types |
C# | I am trying to code a page that is intentionally vulnerable to command injection . This is for a training environment . This is the code I have so far : It seems to work well when it sees a normal request for domain lookup.However , when it sees a request like so : http : //localhost:50159/Home/CommandInjection ? domai... | public ActionResult CommandInjection ( ) { string domain = Request.QueryString [ `` domain '' ] ; ViewBag.Domain = domain ; ProcessStartInfo psi = new ProcessStartInfo ( `` nslookup.exe '' , domain ) { UseShellExecute = false , CreateNoWindow = true , RedirectStandardOutput = true } ; var proc = Process.Start ( psi ) ;... | Coding a page intentionally vulnerable to command injection |
C# | I have 5 textboxes : I want to generate simple SELECT statements using the textbox inputs . To do this I am using parameters and AddWithValue : Now this works just fine , but what I want to do is that if textbox input is empty to handle it with NULL . But as far as I know one ca n't use `` = NULL '' in query , instead ... | < TextBox Name= '' txbFirstName '' / > < TextBox Name= '' txbLastName '' / > < TextBox Name= '' txbCity '' / > < TextBox Name= '' txbAddress '' / > < TextBox Name= '' txbPhone '' / > database.SetQuery ( `` SELECT * FROM tblCustomer WHERE FirstName = @ FirstName AND LastName = @ LastName AND City = @ City AND Address = ... | Pass `` IS NULL '' via parameter |
C# | I found the following code snippet in the DbSet Class of the EntityFramework : I have no idea why the base method is hidden , all the base classes have the method implemented calling base.This is object.GetType ( ) : This is in the DbQuery class : And this is in the DbSet ( DbSet < TEntity > : DbQuery < TEntity > ) cla... | public new Type GetType ( ) { return base.GetType ( ) ; } [ SecuritySafeCritical ] [ __DynamicallyInvokable ] [ MethodImpl ( MethodImplOptions.InternalCall ) ] public extern Type GetType ( ) ; /// < inheritdoc / > [ EditorBrowsable ( EditorBrowsableState.Never ) ] [ SuppressMessage ( `` Microsoft.Design '' , `` CA1024 ... | what is the reason to hide a method with the new keyword , when only returning base.method ? |
C# | I Created and implemented an interface explicitly as below.and Then executed following Main methodand the result I got on console is : Print method is privatePrint method invokedSo my question is why this private method got executed from other class ? As far as I understand the accessibility of private member is restri... | public interface IA { void Print ( ) ; } public class C : IA { void IA.Print ( ) { Console.WriteLine ( `` Print method invoked '' ) ; } } public class Program { public static void Main ( ) { IA c = new C ( ) ; C c1 = new C ( ) ; foreach ( var methodInfo in c.GetType ( ) .GetMethods ( BindingFlags.NonPublic | BindingFla... | Why this private method does get executed from another class ? |
C# | I have been presented a task that I 'm struggling with , in terms of efficiency . I have a database that can have hundreds of thousands of transactions & people . My goal is to find people who commonly have transactions near one another ( Person X has had a transaction within 10 minutes of person Y , on 5 separate occa... | foreach ( var doc in db.Transactions.OrderBy ( d = > d.TransactionID ) ) { foreach ( var doc2 in db.Transactions.Where ( d = > d.TransactionID > doc.TransactionID ) ) { if ( doc2.DateCreated.IsBetween ( doc.DateCreated , minutes ) ) { // hit found } } } | Faster comparison for many DateTime 's |
C# | I have some code that looks like this : It turns out that SomeSaferMethod is not so safe and can also fail in some edge case . For this reason , I created a method called SuperSafeMethod that I want to call in case the SomeSaferMethod also fails in the catch statement.How can I change my try catch so that there 's a th... | string TheString = string.Empty ; try { TheString = SomeDangerousMethod ( ) ; } catch { TheString = SomeSaferMethod ( ) ; } return TheString ; | executing a method in case both the try catch fail |
C# | I have a database that contains 3 tables : PhonesPhoneListings PhoneConditionsPhoneListings has a FK from the Phones table ( PhoneID ) , and a FK from the Phone Conditions table ( conditionID ) I am working on a function that adds a Phone Listing to the user 's cart , and returns all of the necessary information for th... | public ActionResult phoneAdd ( int listingID , int qty ) { ShoppingBasket myBasket = new ShoppingBasket ( ) ; string BasketID = myBasket.GetBasketID ( this.HttpContext ) ; var PhoneListingQuery = ( from x in myDB.phoneListings where x.phonelistingID == listingID select x ) .Single ( ) ; var PhoneCondition = myDB.phoneC... | LINQ : Is there a way to combine these queries into one ? |
C# | I have a generic class Foo < T > where I want to constrain T to be an enum type . Is this possible in C # ? I have triedbut this approach only seem to work for class and struct . Likewise , attempting to constrain T to an underlying enum type will also not work : since int is not a class or interface.EDIT I realize now... | public class Foo < T > where T : enum // COMPILATION ERROR public class Foo < T > where T : int // COMPILATION ERROR | Possible to constrain generic type to enums ? |
C# | I 'm new to programming . I study books . Sometimes some examples raise questions . I ask for help , the explanation on the Habr is not very clear.Found an example on a habr - the fourth question on C # .Explained as follows : In the first call , “ C ” will be displayed , since for var the compiler will infer the type ... | class Program { static void Main ( string [ ] args ) { var x1 = new C ( ) ; x1.Print ( ) ; //C B x2 = new C ( ) ; x2.Print ( ) ; //C A x3 = new C ( ) ; x3.Print ( ) ; //A } } class A { public void Print ( ) { Console.WriteLine ( `` A '' ) ; } } class B : A { new public virtual void Print ( ) { Console.WriteLine ( `` B ... | OOP Method hidden and overloaded |
C# | I am wondering is there anyt c # equivalent for TypeScript 's never typeexample I write this code in TS I will have a build time error.error is : Argument of type 'IRemove ' is not assignable to parameter of type 'never'.This is very useful when someone change the logic in one file and I want to be sure this new case i... | enum ActionTypes { Add , Remove } type IAdd = { type : ActionTypes.Add } ; type IRemove = { type : ActionTypes.Remove } ; type IAction = IAdd | IRemove ; const ensureNever = ( action : never ) = > action ; function test ( action : IAction ) { switch ( action.type ) { case ActionTypes.Add : break ; default : ensureNever... | TypeScript Never type in C # ? |
C# | It 's not entirely obvious to me what 's happening in this situation.I 'd expect both functions to be fired.Either the EventHander class is storing the list of functions to fire as an array - and the array is copied to a new one every time something is added/removed - or when the assignment is made , the whole thing is... | public class Moop { public EventHandler myEvent ; } void Main ( ) { var moo = new Moop ( ) ; moo.myEvent += ( o , sender ) = > { `` Added to Moop # 1 '' .Dump ( ) ; } ; var moo2 = new Moop ( ) ; //Copy the reference , I assume ? moo2.myEvent = moo.myEvent ; moo2.myEvent += ( o , sender ) = > { `` Added to Moop # 2 '' .... | Can someone explain what is happening behind the scenes ? |
C# | I have a POCO class : I want to test some other classes using different values in SomeEntity class . The problem is that I need to test different combinations of many properties . For example : Id = 1 , FirstName = null , LastName = `` Doe '' Id = 1 , FirstName = `` '' , LastName = `` Doe '' Id = 1 , FirstName = `` Joh... | public class SomeEntity { public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } // test that someOtherObject always return the same result // for testObject with ID = 1 and accepts any values from range of // values for FirstName and LastNamevar testObject = new ... | How iterate through combination of POCO properties using It.IsIn ( someRange ) for multiple fields ? |
C# | Having two classes , NodeBase and ContentSectionNode which inherits from the abstract class NodeBase , I 'd like to know if there is any way to avoid repeating a block of code in the ContentSectionNode constructors , while also delegating to the base class constructors.The abstract NodeBase class ctors look like this :... | protected NodeBase ( string tagType , string content ) : this ( ) { TagType = tagType ; Content = content ; } protected NodeBase ( Guid ? parentId , int ? internalParentId , string tagType , string content ) : this ( tagType , content ) { ParentId = parentId ; InternalParentId = internalParentId ; } public ContentSecti... | C # avoid repetition when working with base constructors |
C# | I 'm writing code using a legacy API whose code I can not change . There is a family of methods for supported datatypes ( int , double , bool , string , APIObject ) to do an operation in the API . These take a parameter of the same datatype as indicated in the name of the method . Sample usages as given belowThe return... | GetIntExp ( 5 ) GetStringExp ( `` Hello '' ) GetDoubleExp ( 1.2 ) GetDateExp ( DateTime.Now ) GetAPIObjectExp ( myObject ) | Write a generic method to replace a family of legacy API methods |
C# | I 'm playing around with design patterns , and things are coming along nicely . One thing I 'm unsure of is it worth abstracting out Object creation when there is currently only one object ? For example a project I 'm working on contains two different user types which are not related in any way . They are IStudent and ... | IStudent student = new Student ( ) ; public static class UserFactory { public static T Create < T > ( ) where T : class { if ( typeof ( T ) == typeof ( IStudent ) ) return new Student ( ) as T ; if ( typeof ( T ) == typeof ( IStaff ) ) return new Staff ( ) as T ; throw new Exception ( `` The requested user type is not ... | Is it worth abstracting out Object creation for single classes ? |
C# | So in my normal course of getting some work done , i came across a generic System.NullReferenceException : 'Object reference not set to an instance of an object . '.So no problem i 'm thinking as I start looking for the culprit . After much debugging , I threw my hands up in the air and wanted to give up for the moment... | var data = service.GetData ( someId ) ; var data = new DataType [ ] { } ; using System ; using Dapper.Contrib.Extensions ; namespace some_namespace { # pragma warning disable 1591 [ Table ( `` CompanyOptions '' ) ] public class CompanyOption { [ ExplicitKey ] public Guid PKID { get ; set ; } public Guid CompanyPKId { g... | Illogical NullReferenceException |
C# | I am working in xamarin and trying to consume all services using one method . For that I wrote a TaskExtension . So that from every page in the app I can call that extension method . This is to disable the buttons , show loading screen , response handling and to cater exception handling from one point . I am attaching ... | public static class TaskExtensions { public static async Task < ResultViewModel < U > > ExecuteAsyncOperation < U > ( this Task < HttpResponseMessage > operation , object sender = null ) { ResultViewModel < U > resultModel = new ResultViewModel < U > ( ) ; Button button = BeforeAsyncCall ( sender ) ; try { await Backgr... | Task Extension to Cater App Wide Service Calls |
C# | Why does this : result in an InvalidCastException : Specified cast is not valid . | ( new [ ] { 1,2,3 } ) .Cast < decimal > ( ) ; | .net Trouble casting ints do decimals |
C# | Imagine I have a `` zoo '' mobile app . It fetches `` Animals '' from an online server and stores them in a local database.So I create a class GetAnimalsFromServerService that has the following functions . This does n't compile because T is of type `` Animal '' and not Type `` Bird '' ( and GetBirdsFromServer requires ... | Class AnimalClass Bird : AnimalClass Fish : AnimalClass Pelican : BirdClass Penguin : Bird public Task < Animal [ ] > GetAnimalsFromServer < T > ( ) where T : Animal , new ( ) { if ( typeof ( T ) == typeof ( Bird ) ) { return GetBirdsFromServer < T > ( ) ; } else if ( typeof ( T ) == typeof ( Fish ) ) { return GetFishF... | c # How do I cast and pass a generic type parameter to an internal function ? |
C# | As far as I can understand using view models can make web dev . life much easier , in sense that we can use this approach for display only needed properties in localized strings . Also I use in mvc3 view models jquery validation , etc . Right now I 'm in doubt since I have expirience real bottleneck in my webapp . with... | List < Domain.Property > data = session.Query < Domain.Property > ( ) .ToList ( ) ; return PropertyViewModel.FromDomainModel ( data ) ; List < PropertyViewModel > dataVm = new List < PropertyViewModel > ( ) ; { foreach ( Property p in x ) { dataVm.Add ( new PropertyViewModel ( p ) ) ; } return dataVm ; } public Propert... | Does ViewModel decrease web apps performace |
C# | The form I 'm trying to develop has an array of 6 picture boxes and an array of 6 die images . I have a button that when clicked needs to create 6 threads that `` roll '' the dice , showing each image for a moment . The problem I 'm having is that I need to call a method within button click after the dice have been rol... | namespace testDice { public partial class Form1 : Form { private Image [ ] imgAr ; private PictureBox [ ] picBoxAr ; private Random r ; private Thread [ ] tArray ; private ThreadStart tStart ; private delegate void setTheImages ( ) ; public Form1 ( ) { InitializeComponent ( ) ; setImageArray ( ) ; setPicBoxAr ( ) ; } p... | Problems with my threads array |
C# | Possible Duplicate : Difference between Convert.tostring ( ) and .tostring ( ) HiCarrying on from this question What is the difference between Convert and Parse ? Here are two lines of code.My question is what is the difference and which would be best to use ? Thank you in advance . | Convert.ToString ( myObject ) ; myObject.ToString ( ) ; | Difference between converting strings |
C# | What I have is a stage , some interfaces , and also registration section . The problem is I need to defined some parameters as fixed and others as variables.Is it possible with windsor container to define a parameter connection in declaration , and take IDosomething and IDoMatch from the container ? That is the concret... | interface IDoSomething { void DoWork ( ) ; } interface IDoMath ( ) { void DoWork ( ) ; } interface IBehaviorBusiness { void Do ( ) ; } class BehaviorBusiness { ... public BehaviorBusiness ( IDoSomething doSomething , IDoMatch doMatch , string connection ) { } ; ... } container.Register ( Component.For < IDoSomething > ... | Specify for constructor class fixed values and other variables from container |
C# | I was practicing enums in C # , and I am not able to understand the output of theseFor this test my enum and output areI thought at rum time program chooses the 1st item with value 0 , to confirm this I assigned value of 0 to BottomThen I thought maybe program chooses the 1st item with value 0 but searches alphabetical... | void Main ( ) { MyEnum a = MyEnum.Top ; Console.WriteLine ( a ) ; } enum MyEnum { Left , Right , Top , Bottom // Top } enum MyEnum { Left , Right , Top = 0 , Bottom // Left } enum MyEnum { Left , Right , Top = 0 , Bottom = 0 // Bottom } void Main ( ) { MyEnum a = MyEnum.ATop ; Console.WriteLine ( a ) ; } enum MyEnum { ... | Can not understand the behavior of Enums |
C# | I have a products table like this : -I want to find the products who have maximum price for each productId.Sample Output : -I have tried this query : -This query is working fine , but my question is should i use OrderByDescending twice ? I mean since i just want single item based on 1 property and suppose there are mul... | ProductID ProductName Price 1 Milk 10 2 Banana 20 3 Apple 15 1 Grapes 12 2 Banana 25 1 Milk 8 ProductID ProductName Price 1 Grapes 12 2 Banana 25 3 Apple 15 List < Product > groups = products .GroupBy ( p = > p.ProductId ) .Select ( p = > new Product { ProductId = p.Key , Name = p.OrderByDescending ( o = > o.Price ) .F... | Should I use OrderByDescending twice in LINQ ? |
C# | I decompiled some unity dll files in dnspyand got this linei need to know about the fieldof ( ) function in that line i have n't seen it before ( because i 'm a beginner ) and two why it shows an error in that line | RuntimeHelpers.InitializeArray ( array , fieldof ( < PrivateImplementationDetails > .51A7A390CD6DE245186881400B18C9D822EFE240 ) .FieldHandle ) ; | what is `` fieldof ( ) '' method in c # |
C# | I have some basic app on windows phone 8.1 , and in that i have regular buttons , for navigate or exit application . I want to disable HardwareButton for back/exit , so if anyone press it , application will not exit.Any help ? Btw , i tried : | Public void HardwareButtons_BackPressed ( object sender , Windows.Phone.UI.Input.BackPressedEventArgs e ) { e.Handled = false ; } | DIsable HardwareButton on Windows Phone 8.1 |
C# | Given the following classes : This test fails ( unexpectedly ) : And this test passes ( expectedly ) : Why does the first test result in a count of 3 ? | public class WeekOfYear : IEquatable < WeekOfYear > , IComparable < WeekOfYear > { private readonly DateTime dateTime ; private readonly DayOfWeek firstDayOfWeek ; public WeekOfYear ( DateTime dateTime ) : this ( dateTime , DayOfWeek.Sunday ) { } public WeekOfYear ( DateTime dateTime , DayOfWeek firstDayOfWeek ) { this... | Why does this LINQ grouping have a count of 3 instead of 2 ? |
C# | I have following C # code compiled as Sort.exe : I have a file input.txt which has following 5 lines as its content : Now if I run it on command prompt following is the output : I am not able to understand what kind of string sorting it is where string starting with x- ( 3rd line in output ) comes in middle of strings ... | using System ; using System.Collections.Generic ; class Test { public static int Main ( string [ ] args ) { string text = null ; List < string > lines = new List < string > ( ) ; while ( ( text = Console.In.ReadLine ( ) ) ! = null ) { lines.Add ( text ) ; } lines.Sort ( ) ; foreach ( var line in lines ) Console.WriteLi... | String sorting gotcha |
C# | My program uses the code : Fairly regularly . I was just curious about how this is handled by the compiler . Is it stored as a static double or is it executed in run time ? | Convert.ToDouble ( Int32.MaxValue ) | Does C # compiler convert and store static variables ? |
C# | When I compile a UWP app with the .NET Native compiler and turn on code optimizations ( essentially release mode ) , then I get a NullReferenceException when I try to access the actual exception in the catch block.Code Sample : It goes into the correct catch block , and throws a NullReferenceException when I access ex ... | try { throw new ArgumentNullException ( `` Param '' ) ; } catch ( ArgumentNullException ex ) when ( ex.ParamName == `` Param '' ) { ErrorBlock.Text = ex.ParamName ; // ErrorBlock is a TextBlock in the xaml } catch ( Exception ) { } | Code in filtered exception handler throws NullReferenceException when accessing exception |
C# | I note thatIs a sound C # statementBut that the expressionReturns false . Is n't this a contradiction ? | int number = ' a ' ; typeof ( int ) .IsAssignableFrom ( typeof ( char ) ) | Is int assignable from char ? |
C# | Typically , for code that I do n't expect to throw exceptions but does ( i.e . a programming error ) , I want my application to crash ( so that it does n't corrupt data , report invalid data to the user , etc. ) . Is there a best practice for getting ( closer to ) this behavior when using Tasks ? We 've registered a ha... | var t1 = Task.Factory.StartNew ( ( ) = > { try { string path = null ; // Programming error . Should have been a valid string . Will cause System.ArgumentNullException below using ( FileStream fs = File.Create ( path ) ) { } } catch ( System.IO.IOException ) { throw ; } // Expected possible exception catch ( System.Unau... | Getting a Task 's unexpected Exception to bring down the application earlier than Garbage Collection |
C# | Can anyone explain why this works : but if I change the object types of the locking objects to a String ( as below ) it fails : It 's been confusing me for a while now . Thanks : ) | Object ready_lock = new Object ( ) ; Object thread_lock = new Object ( ) ; public static bool able_to_get_lock = false ; public void GetThreadLock ( ) { if ( Monitor.TryEnter ( thread_lock,2 ) ) { able_to_get_lock = true ; } } [ TestMethod ] public void ThreadingModelTest ( ) { Monitor.Enter ( ready_lock ) ; Thread t1 ... | c # threading behaviour |
C# | MSDN states that : By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code ; the compiler adds the calls.They also give this example , using the newer collection initialization syntax with brackets : However , when checking the IL code generated , i... | var numbers = new Dictionary < int , string > { [ 7 ] = `` seven '' , [ 9 ] = `` nine '' , [ 13 ] = `` thirteen '' } ; IL_0007 : ldstr `` seven '' IL_000c : callvirt instance void class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < int32 , string > : :set_Item ( ! 0/*int32*/ , ! 1/*string*/ ) // C # code : v... | Difference Between Collection Initializer Syntaxes |
C# | Consider the following xml : I want to be able to get Inner1 's value ( `` ABC '' ) without parsing the whole document . This is because in reality the document might be quite long . Is there a way to do this using .net ( XDocument . As opposed to manually parsing it ) ? | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Outer > < Inner1 > ABC < /Inner1 > < Inner2 > DEF < /Inner2 > < /Outer > | Parse only part of xml |
C# | I 've started to code a image processing program from different image processing algorithms , mostly from René Schulte work , and when benchmarking , I noticed that from all the effects I could find from different sources , a code for applying a 'Softlight ' effect was the slowest . I 'm not good in optimizing equation... | // Basically , b is from Image A , and t from Image Bint csoftLight ( float b , float t ) { b /= 255 ; t /= 255 ; return ( int ) ( ( t < 0.5 ) ? 255 * ( ( 1 - 2 * t ) * b * b + 2 * t * b ) : 255 * ( ( 1 - ( 2 * t - 1 ) ) * b + ( 2 * t - 1 ) * ( Math.Pow ( b , 0.5 ) ) ) ) ; } // Input : 137 and 113// Byte version : int ... | Is this formula repetitive or optimal |
C# | I have the following extensions class : If I create a tuple and invoke Match ( ) , it correctly uses the first extension method : If I create a int and invoke Match ( ) , it correctly uses the last extension method : However if I create SomeClass , which implements ITupleMatchable < int , string > and try and match on ... | public static class MatcherExtensions { public static ExecMatcher < T1 , T2 > Match < T1 , T2 > ( this Tuple < T1 , T2 > item ) { return new ExecMatcher < T1 , T2 > ( item.Item1 , item.Item2 ) ; } public static ExecMatcher < T1 , T2 > Match < T1 , T2 > ( this ITupleMatchable < T1 , T2 > item ) { var tuple = item.Proper... | Are extension methods for interfaces treated as lower priority than less specific ones ? |
C# | What does `` From any class-type S to any interface-type T , provided S is not sealed and provided S does not implement T. '' actually mean ? I came across this in the C # Language Specifications here : 6.2.4 Explicit reference conversions The explicit reference conversions are : ... From any class-type S to any interf... | class S { } //not sealed , nor does it implement Tinterface T { } ... T t = ( T ) new S ( ) ; //will throw InvalidCastException . | What does `` From any class-type S to any interface-type T , provided S is not sealed and provided S does not implement T. '' actually mean ? |
C# | I have a TreeView that looks like this : The ItemsSource is a keyed resource that goes by the name of InspectionTypeGroupViewSource : The role of this little thing is to take the ViewModel 's Results property : ... and group it on two levels - first by InspectionType , then by Inspection - the result is a 3-level hiera... | < TreeView Grid.Row= '' 1 '' x : Name= '' InspectionResultsTreeView '' ItemsSource= '' { Binding Source= { StaticResource InspectionTypeGroupViewSource } , Path=Groups } '' ItemTemplate= '' { StaticResource InspectionTypeGroupsTemplate } '' > < /TreeView > < CollectionViewSource x : Key= '' InspectionTypeGroupViewSourc... | What 's an idiomatic XAML TreeView with CollectionViewGroup groupings ? |
C# | Does using the null-conditional operator duplicate null checks ? For exampleDoes that get compiled into this : Or this ? If the former , does it make a difference if there is other code in between both lines ? In other words , how smart is the compiler/optimizer ? | var x = instance ? .Property1 ; var y = instance ? .Property2 ; if ( instance ! = null ) { var x = instance.Property1 ; var y = instance.Property2 ; } if ( instance ! = null ) { var x = instance.Property1 ; } if ( instance ! = null ) { var y = instance.Property2 ; } | Is the Null-Conditional operator optimized across consecutive usages sites or does it result in duplicate checks ? |
C# | Consider the following code : Null propagation returns T , rather than Nullable < T > .How and why ? | Nullable < DateTime > dt ; dt . < -- Nullable < DateTime > dt ? . < -- DateTime | Why does null-propagation of Nullable < T > return T and not Nullable < T > ? |
C# | Is there a way to do it like : | return ( Page is WebAdminPriceRanges || Page is WebAdminRatingQuestions ) ; return ( Page is WebAdminPriceRanges || WebAdminRatingQuestions ) ; | `` is '' c # multiple options |
C# | I have a problem with validating my XML file , after it has been automatically formatted . The validation does n't trim the string before validating it . Is this a bug in the implementation of the XML validation of .NET or is this accepted behavior ? If it is accepted behavior , how are cases like this normally handled... | < xs : schema ... > ... < xs : simpleType name= '' ItemTypeData '' > < xs : restriction base= '' xs : string '' > < xs : enumeration value= '' ItemA '' / > < /xs : restriction > < /xs : simpleType > < /xs : schema > ... < ItemType > ItemA < /ItemType > ... ... < ItemType > ItemA < /ItemType > ... | Schema validation not trimming strings before validating |
C# | I 'm trying to create my own class from System.Windows.Forms.ButtonI have a problem with Designer.cs behavior - default value is not working properly . I expect , that when MyButton is added to form , it has Size of 100x200 , but it is not set through Designer.cs , so when in MyButton constructor I change Size to 200x2... | public class MyButton : Button { public MyButton ( ) : base ( ) { Size = new Size ( 100 , 200 ) ; } [ DefaultValue ( typeof ( Size ) , `` 100 , 200 '' ) ] public new Size Size { get = > base.Size ; set = > base.Size = value ; } } | Prevent Size property from being serialized when it 's equal to default value |
C# | I wrote this very basic programm to examine what the compiler is doing behind the scenes : Now when I look at the code with Reflector I do see that the compiler generates a class for my closure like that : That 's fine and I 'm aware that he needs to do that to handle my closure . However , what I ca n't see is how he ... | class Program { static void Main ( string [ ] args ) { var increase = Increase ( ) ; Console.WriteLine ( increase ( ) ) ; Console.WriteLine ( increase ( ) ) ; Console.ReadLine ( ) ; } static Func < int > Increase ( ) { int counter = 0 ; return ( ) = > counter++ ; } } [ CompilerGenerated ] private sealed class < > c__Di... | Ca n't see how the compiler uses the classes he creates for my closures |
C# | Just to clarify , is it really mandatory that all the members of a child class are declared on the abstract class above it ? Would be possible something like this : It 's just an example ... In such case , the property MyName is not defined in the parent class , but it is in the child class ... Is it possible ? Thanks ... | public abstract class MyParent { public int x { get ; set ; } } public class MyChild : MyParent { public int x { get ; set ; } public string MyName { get ; private set ; } } | Is it possible to define member on a child class without defining it on the abstract parent class ? C # |
C# | Could you please explain why the output of those two functions is different for the same data ? I expected them to produce the same output i.e . append lines . How can I change alternative 1 to add lines ? ( Background Measurements implements ICollection < > ) Alternative 1- > no output/added linesAlternative 2- > adde... | private void CreateBody ( TestRun testRun , StringBuilder lines ) { testRun.Measurements.OrderBy ( m = > m.TimeStamp ) .Select ( m = > lines.AppendLine ( string.Format ( `` { 0 } , { 1 } '' , m.TestRound , m.Transponder.Epc ) ) ) ; } private void CreateBody2 ( TestRun testRun , StringBuilder lines ) { foreach ( Measure... | Linq expression and foreach produce different results |
C# | Jon Skeet brought up this issue once in his videos ( though did n't provide with an answer ) .Let 's say we have a Class named Personand the Person class has Name propertyThen we have another class , Spy.Of course a Spy is a Person so we will derive from the Person class.We do n't want people to know the Spy 's name so... | public class Person { public string Name { get ; set ; } } public class Spy : Person { } static void ReportSpy ( Spy spy ) { string name = spy.Name ; } static void ReportSpy ( Spy spy ) { Person spyAsPerson = spy ; string name = spyAsPerson.Name ; } | hiding property from derived class |
C# | I do n't know what to call this , which makes googling harder.I have an integer , say 3 , and want to convert it to 11100000 , that is , a byte with the value of the integers number of bits set , from the most significantly bit.I guess it could be done with : but is there anything faster / more nice or , preferably , s... | byte result = 0 ; for ( int i = 8 ; i > 8 - 3 ; i -- ) result += 2 ^ i ; | Integer to byte with given number of bits set |
C# | Let 's say I have a list of Points.How can I group this Points , so that all Points with the same x- and y-value are in one group , till the next element has other values ? The final sequence should look like this ( a group of points is enclosed with brackets ) : Note that the order has to be exactly the same . | { ( 0,0 ) , ( 0,0 ) , ( 0,1 ) , ( 0,0 ) , ( 0,0 ) , ( 0,0 ) , ( 2,1 ) , ( 4,1 ) , ( 0,1 ) , ( 0,1 ) } { ( 0,0 ) , ( 0,0 ) } , { ( 0,1 ) } , { ( 0,0 ) , ( 0,0 ) , ( 0,0 ) } , { ( 2,1 ) } , { ( 4,1 ) } , { ( 0,1 ) , ( 0,1 ) } | How can I group a sequence by two values and keep the order of the sequence ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.