lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | Have been playing around with the 4.0 DLR and was comparing dynamic to object and came across this : Code : Result : x = 10 and is a System.Int32 . x = 13 and is a System.Int32 . x = 13a and is a System.String.To me , it looks like object tries to fit the object to a type at runtime ( dynamic ) . However if I do n't ca... | object x = 10 ; Console.WriteLine ( `` x = { 0 } and is a { 1 } .\n '' , x , x.GetType ( ) ) ; x = ( int ) x + 3 ; Console.WriteLine ( `` x = { 0 } and is a { 1 } .\n '' , x , x.GetType ( ) ) ; x = x + `` a '' ; Console.WriteLine ( `` x = { 0 } and is a { 1 } .\n '' , x , x.GetType ( ) ) ; | C # object looks like dynamic type |
C# | I have a method that uses Regex to find a pattern within a text string . It works , but is n't adequate going forward because it requires the text to appear in the exact order , rather than viewing the phrase as a set of words.This version improves upon the previous version , in that it does allow the words to be match... | public static string HighlightExceptV1 ( this string text , string wordsToExclude ) { // Original version // wordsToExclude usually consists of a 1 , 2 or 3 word term . // The text must be in a specific order to work . var pattern = $ @ '' ( \s*\b { wordsToExclude } \b\s* ) '' ; // Do something to string ... } public s... | Split string into words and rejoin with additional data |
C# | I am using Csharp Linq to create the following report I have two tables as belowThe report contains I have tried the following , using joinon the second 'where ' a Error is displayed thank you for any assistance | # Usersnid pid name1 1 name12 1 name2 # Transactionsnid tid location dcode 1 T1 L1 D12 T1 L2 D12 T2 L1 D12 T2 L3 D1 a ) columns from users table where nid ! = pid b ) columns from transactions where tid == T2 and nid = results from a ) c ) the combination can have only one top row in result nid name tid Location2 name2... | using linq with join using two where on two tables |
C# | I have a piece of code which looks a little like this : CC is giving me a warning : Warning 301 CodeContracts : Consider adding the postcondition Contract.Ensures ( Contract.Result ( ) ! = null ) ; to provide extra-documentation to the library clientsWhich is obviously completely redundant ! I have several such redunda... | public TReturn SubRegion ( TParam foo ) { Contract.Requires ( foo ! = null ) ; Contract.Ensures ( Contract.Result < TReturn > ( ) ! = null ) ; if ( ! CheckStuff ( foo ) ) foo.Blah ( ) ; return OtherStuff ( foo ) ; } | CC Suggesting Redundant Ensures |
C# | suppose i have the following group of static functionshere i sent the variable by reference : and here i sent the variable by valuewhich one makes more sense , and is there any performance difference between the 2 ? | public static void ProcessEmailMessage ( ref string HTML ) { ModifyLinks ( ref HTML ) ; AddFakeImage ( ref HTML ) ; } public static void ModifyLinks ( ref string HTML ) { //modify HTML links } public static void AddFakeImage ( ref string HTML ) { //adds an image to the HTML } public static string ProcessEmailMessage ( ... | which is better in this case , return or ref |
C# | See the code below , I just want to understand the reason behind that ... | const int a = 2147483647 ; const int b = 2147483647 ; int c = a + b ; // it does n't allow to compile ! ! ! int a = 2147483647 ; int b = 2147483647 ; int c = a + b ; // it allows to compile ! ! ! | why CLR does n't compile overflow const and but for variables it does ? |
C# | I have an Action that receives a class with a dictionary in its properties : If I do a post to my action with the following JSON : The key in my dictionary is stripped to the dot and has nothing in the value . Trying without the dot works . How can I do a post with a dot in a Dictionary < string , string > with MVC ? | public ActionResult TestAction ( TestClass testClass ) { return View ( ) ; } public class TestClass { public Dictionary < string , string > KeyValues { get ; set ; } } { `` KeyValues '' : { `` test.withDoT '' : `` testWithDot '' } } | Controller 's action with dictionary as parameter stripping to dot |
C# | As we all know , we can not write code like this in current version of C # : but we may use new ( ) constrain to enforce that T has public parameter-less constructor , and then we are able to create new instances of T using new T ( ) expression.There is plenty of answers on SO about various workaround , but non of them... | public class A { public static void Method < T > ( ) where T : new ( string , string ) { var x = new T ( `` foo '' , `` bar '' ) ; } } | Why there is no constructor-with-parameters constrain on generic parameters in C # ? |
C# | I have two methods , both of them compiles correctly : In the second case ( method B ) compiler is smart enough to detect that variable i is never used so it does n't complain about not assigning it.However , I have another example ( a combination of both ) that seems to be equivalent to method B : When compiling on Wi... | public int A ( ) { int i ; if ( ! int.TryParse ( `` 0 '' , out i ) ) { return -1 ; } // do sth return i ; } public int B ( ) { int i ; if ( true ) { return -1 ; } return i ; } public int C ( ) { int i ; if ( true || ! int.TryParse ( `` 0 '' , out i ) ) { return -1 ; } return i ; } | Unassigned local variable and short-circuit evaluation |
C# | I just had a unit test fail for a strange reason involving IDictionary < object , object > .IDictionary < K , V > has two Remove methods . One takes a K , the other takes a KeyValuePair < K , V > . Consider these two dictionaries that are very similar to each other , but do n't quite act the same : The output is True ,... | IDictionary < string , object > d1 = new Dictionary < string , object > ( ) ; IDictionary < object , object > d2 = new Dictionary < object , object > ( ) ; d1.Add ( `` 1 '' , 2 ) ; d2.Add ( `` 1 '' , 2 ) ; Console.WriteLine ( d1.Remove ( new KeyValuePair < string , object > ( `` 1 '' , 2 ) ) ) ; Console.WriteLine ( d2.... | How does this overload resolution make any sense ? |
C# | I have the following in visual studio , and its not complaining : my guess is this will throw an exception somewhere at runtime , but why is visual studio allowing this ? Just because it could be null ? Is a null int treated the same way as a null string ? | int ? int1 ; int ? int2 ; string str = int1 + `` - '' + int2 ; | why is the concatenation of an int and a string not complaining at compile time |
C# | Will someone please put me out of my misery and let me know what I have/have not done that makes my code fail ? I am using Entity Framework database first . When I query for an entity and request a related entity to be included , I get this error : Invalid column name 'PrimaryContact_ContactID ' . The exception is thro... | //Enterprisepublic class Enterprise { public int Id { get ; set ; } public string Name { get ; set ; } public int CompanyID { get ; set ; } public virtual Company Company { get ; set ; } } //Companypublic class Company { public int Id { get ; set ; } public string Name { get ; set ; } public int PrimaryContactId { get ... | Getting Sql Error : Invalid column name 'PrimaryContact_ContactID ' |
C# | I have 3 ObservableCollections in my ViewModel and one Class which I load when you run an app.To ensure ObservableCollections are deserialized I just got.If there is no file , deserializationMethod will create new object withThat works fine - no problem with that.And for class I haveI added a property - if file is dese... | if ( SomeCollection.Count == 0 ) ThisCollection = await deserializationMethod < ObservableColletion < T > > ( filename ) ; return Activator.CreateInstance < T > ( ) ; if ( ClassObject.Loaded ! = true ) ThisObject = await deserializationMethod < T > ( filename ) ; | Ensure data deserialization / serialization |
C# | I have trouble deleting the duplicate references in my list.I have this listwith my class SaveMongo that looks like this Whenever I want to add an element to my list I use the following codeHowever , I sometimes get duplicates references . I tried using thisto delete them . Without success.I also tried to do thisStill ... | List < SaveMongo > toReturn public class SaveMongo { public ObjectId _id { get ; set ; } public DateTime date { get ; set ; } public Guid ClientId { get ; set ; } public List < TypeOfSave > ListType = new List < TypeOfSave > ( ) ; public List < ObjectId > ListObjSave = new List < ObjectId > ( ) ; public SaveMongo ( ) {... | Deleting duplicates references in list c # |
C# | I have a text file who are like this : I want to put # before product . and the file to be : For this I use next code : But this code do the next thing : Someone can explain me way ? And how I can write just one # before that rows ? | Rows ... product.peopleproduct.people_goodproduct.people_badproduct.boy # product.me ... Rows Rows ... # product.people # product.people_good # product.people_bad # product.boy # product.me ... Rows string installerfilename = pathTemp + fileArr1 ; string installertext = File.ReadAllText ( installerfilename ) ; var linI... | How to write just an # before some rows in a text file ? |
C# | I ' m writing desktop Project in C # . I 'm using Nhibernate to communicate with database . Moreover I use FluentNhibernate into mapping of models but I 'm stuck in some part of mapping . Here is My mapping Class in ProductMapLoosing Maphere is CurrencyMapCurrencyMaphere is I have in my currency table one primary key a... | public LosingMap ( ) { Id ( x = > x.id ) ; Map ( x = > x.reason ) ; Map ( x = > x.quantity ) ; Map ( x = > x.lose_sum ) ; Map ( x = > x.rate ) ; Map ( x = > x.deleted ) ; Map ( x = > x.create_date ) ; Map ( x = > x.update_date ) ; References ( x = > x.currency ) .Column ( `` CurrencyCode '' ) ; Table ( `` Loosing '' ) ... | FluentNhibernate mapping of two tables oneToMany using unique instea of primary key in mapping |
C# | What is the difference between these two methods ? first : second : | public static int Foo < T > ( T first , T second ) where T : IComparable { return first.CompareTo ( second ) } public static int Foo ( IComparable first , IComparable second ) { return first.CompareTo ( second ) ; } | Generic version vs interface version of a method |
C# | I have one abstract class named A , and other classes ( B , C , D , E , ... ) that implements A.My derived classes are holding values of different types.I also have a list of A objects ... .where the .val is not known by the base-class ofc.How can i get this dynamic behaviour ? I do n't want to use getType in a long sw... | abstract class A { } class B : class A { public int val { get ; private set ; } } class C : class A { public double val { get ; private set ; } } class D : class A { public string val { get ; private set ; } } class Program { static void Main ( string [ ] args ) { List list = new List { new B ( ) , new C ( ) , new D ( ... | calling derived methods on a baseclass collection |
C# | Let 's say we have code as follows : When the action AdvanceTokenCallback is called from external API the token variable in the CreateWorkItem action becomes a null.However in a case when I create a `` bridge '' action and move the logic which creates the cookie there , then the token located in CreateWorkItem contains... | public class HomeController : Controller { [ HttpPost ] public IActionResult AdvanceTokenCallback ( string apiToken ) { Response.Cookies.Append ( `` Token '' , apiToken , new Microsoft.AspNetCore.Http.CookieOptions ( ) { Path = `` / '' , Expires = _tokenCookieExpirationTime } ) ; return RedirectToAction ( nameof ( Crea... | Action does n't create a cookie when its called by external API |
C# | I want to separate IEnumerable variables by their types . My code is like this : When I use type.GetType ( ) .GetGenericTypeDefinition ( ) .Name , the listGenericType is like List ` 1 or HashSet ` 1 but I want it like List or HashSet . Thus , I used Substring to handle this issue ! Is there anyway to handle this proble... | if ( type is IEnumerable ) { var listGenericType = type.GetType ( ) .GetGenericTypeDefinition ( ) .Name ; listGenericType = listGenericType.Substring ( 0 , listGenericType.IndexOf ( ' ` ' ) ) ; if ( listGenericType == `` List '' ) { //do something } else if ( listGenericType == `` HashSet '' ) { //do something } } if (... | how to get only the type of Enumerable ? |
C# | When we write code like the one given below ( in the console Main ) , Are we , in fact , instantiating the employee class ? The employee class contains get and set for serial no , name , and a List for job title and constructor as well.My question is it like the basic instantiation as below . | List < Employee > employee = new List < Employee > ( ) ; employee.Add ( new Employee ( 1 , '' Thomas Alva Edison '' , new string [ ] { `` Inventor '' } ) ) ; Employee e1=new Employee ( 1 , '' Thomas Alva Edison '' , new string [ ] { `` Inventor '' } ) ) | Class instantiation when several values/string are involved |
C# | I 've just recently started using LINQ on a daily basis . I 've read quite a lot about L2E queries should be compiled to improve performance using the following : Using LINQ-To-Entities 4.0 I ran a query 10 times uncompiled and then compiled and yielded the following results in seconds : As you can see there 's not a r... | CompiledQuery.Compile ( query ) ; // Sample Queryfrom u in ctx.Users orderby u.Id , u.Username select uUncompiled Compiled -- -- -- -- -- -- -- -- -- -- -0.295 0.29461740.024 0.02204620.008 0.00601260.013 0.02104410.007 0.0100210.011 0.0100210.008 0.00601260.009 0.00701470.008 0.0060126 | Are LINQ to Entites 4.0 Queries Compiled By Default ? |
C# | New to .NET Core . What am I doing wrong ? Here is my controllerI am able to call the API with this URLhttp : //localhost:51375/api/customer/8172858817I hit the breakpoint in GET method , but Id is always zero . I can not get the method to read the value which is being passed from URL.Any suggestions ? | [ Route ( `` api/ [ controller ] '' ) ] public class customerController : Controller { // GET : api/values // [ HttpGet ] //public IEnumerable < string > Get ( ) // { // return new string [ ] { `` value1 '' , `` value2 '' } ; // } // GET api/values/5 [ HttpGet ( `` { id } '' ) ] public customer Get ( int id ) { var rep... | .Net Core Web API |
C# | I 'm experimenting with the simple AR multiplayer app , made using this tutorial : https : //www.youtube.com/watch ? v=n3a-aaSYR8sSourceCodeIt works ! But I 'm not sure , why 2 objects which were instantiated the same way positioned differently : The moon and the player.Why does the `` Player '' game object remain atta... | PhotonNetwork.Instantiate ( `` SampleMoon '' , Vector3.zero , Quaternion.identity , 0 ) ; | Need clarification of one thing in this AR Multiplayer Tutorial |
C# | Linq is pretty powerful , but sometimes I can find myself rushing to make extensions and I later wonder if I could do it with native methods . So , is it possible to implement the following without using an extension ? | /// < summary > /// Removes duplicates that are immediately clustered together./// < /summary > public static IEnumerable < TData > DistinctLocal < TData > ( this IEnumerable < TData > enumerable ) { bool yielded = false ; TData last = default ( TData ) ; foreach ( var item in enumerable ) { if ( yielded == false || la... | Linq - Locally Distinct |
C# | While studying the pointer through unsafe , I noticed something strange . result 11530536 A 11530532 B 111 *C 11530528 & C 11530536 C 7143424 ~ 7176192 original 32768 33448 memory 1st , why is it outside the start and end addresses of the applications ? I know it 's divided into a heap and a stack , but I 've added a c... | unsafe class Program { static unsafe void Main ( string [ ] args ) { int A = 111 ; int B = 222 ; int* C = & A ; Console.WriteLine ( `` { 0 } A '' , ( int ) & A ) ; Console.WriteLine ( `` { 0 } B '' , ( int ) & B ) ; Console.WriteLine ( `` { 0 } *C '' , ( int ) *C ) ; Console.WriteLine ( `` { 0 } & C '' , ( int ) & C ) ... | c # why is `` unsafe '' out of range between Application Address |
C# | Something is not clear to me , according to what I read : Field Initializers run before Constructors.Static field Initializers execute before the static constructor is called ( which is still compatible with point 1 . ) .If a type has no static constructor , field Initializers will execute before the type being used ( ... | class Program { static void Main ( string [ ] args ) { Console.WriteLine ( Foo.X ) ; Console.ReadLine ( ) ; } } class Foo { public static Foo Instance = new Foo ( ) ; public static int X = 3 ; Foo ( ) { Console.WriteLine ( `` In constructor : `` + X ) ; } } public static Foo Instance = new Foo ( ) ; | Fields Initilizers ( Static or not ) and Constructor ( Static or not ) which one runs first |
C# | I 've been using Resharper 2016 with Visual Studio 2015 , and I had code formatted like this : And life was beautiful ... But after updating to Visual Studio 2017 , and to Resharper 2018 , suddenly after hitting ctrl + E + C , and performing built-in R # option `` Reformat code '' , I got this : Which is terrible , bec... | list.Add ( new SomeClass { Value = 1 , Name = `` some name '' } ) ; list.Add ( new SomeClass { Value = 1 , Name = `` some name '' } ) ; | Why is Resharper breaking line after method opening brace and how to prevent it ? |
C# | I am getting format exception inI try catching it by try-catch but exception is still thrown by app level try catch and not caught by my local try catch.Why my try catch not getting error ? | try { return strngarray.Select ( strngarrayelem = > { string [ ] data = strngarrayelem .Split ( ' , ' ) ; return new xyzClass ( data [ 1 ] , data [ 2 ] , data [ 0 ] , ( Color ) System.Windows.Media.ColorConverter.ConvertFromString ( data [ 3 ] ) , data.Length > 4 ? data [ 4 ] : `` N/A '' ) ; } ) ; } catch ( Exception e... | try catch skipping exception |
C# | I come from a C++ background and I am relatively new to C # . Currently , I am trying to write two print functions , the first of which accepts a generic array parameter ( and prints the items of the array to the command line ) and a second one which accepts a generic primitive parameter ( and invokes its ToString ( ) ... | using System ; namespace OverloadResolution { class Program { static void Main ( string [ ] args ) { string [ ] foo = new string [ ] { `` A '' , `` B '' , `` C '' } ; Extensions.PrintMe ( foo ) ; Extensions.PrintMe ( `` Hello world '' ) ; Console.ReadLine ( ) ; } } public static class Extensions { public static void Pr... | C # overload resolution with generics |
C# | When I run the codeMy computer makes a noise , I have confirmed this to work on a Windows 7 computer as well , I am using windows 10 . My assumption is that it either has to do with how Unicode or the console handles this character but I 'm not really certain . Any help understanding this would be greatly appreciated . | Console.WriteLine ( Convert.ToChar ( Convert.ToByte ( 7 ) ) ) | Console.WriteLine ( ) Making a a sound when Convert.ToChar ( 7 ) is put in it |
C# | Do n't think the title can explain what i 'm on about and it 's a bit difficult to explain , so i 'll let the code do the talking . You can copy+paste this into LINQPad and run it as a C # program , or make the necessary adjustments as a regular c # project in visual studio ( e.g . : change calls to Dump ( ) to Console... | void Main ( ) { doStuff < a , b > ( ) ; } public void doStuff < TA , TB > ( ) where TA : class , Ia , new ( ) where TB : class , Ib , new ( ) { Iab < TA , TB > x = null ; x = new generic1 < TA , TB > ( ) ; x.Go ( ) .Dump ( ) ; //x = new generic2 < TA > ( ) ; // < - Can not implicitly convert type 'UserQuery.generic2 < ... | Generic object needs a cast even though it implements the required interface |
C# | I am writing code for Unity , using C # . At present , I am dealing with a few smaller classes and structures , in effort to quickly serialise a randomly generated map . In doing so , I deal with a few constructors that also take some of these smaller classes and structures , as parameters.In the past , I would typical... | public class Tile { public GridCoordinates position ; public TileCode prefabID ; } public struct GridCoordinates { public int x ; public int y ; } public struct TileCode { public int categoryID ; public int individuaID ; } public class Tile { public GridCoordinates position ; public TileCode prefabID ; public Tile ( Ti... | Is it bad form to provide excessive overloads for a method or constructor in C # ? |
C# | Let 's say I have code like this : To make it clear , I want to store the vertices and indices inside it in the constructor . I 've not worked very much with C # so I 'm not sure how the convention looks . Am I supposed to make a copy of the entire list or can I just copy the reference ? What 's the convention ? | private IList < Vector3 > vertices ; private IList < uint > indices ; public Mesh ( IList < Vector3 > vertices , IList < uint > indices ) { // ? ? ? } | What is the convention for passing in a list to a constructor and then storing it ? |
C# | I have a Task table ( called Task_Task ) and a Field table ( called Core_Field ) . I also have Task_Field table that links the two in many to many relationship : I need to insert a number of records into this table . I 'm doing it like this : This leads to the following trace : In this case we had 5 guids in List < Gui... | CREATE TABLE [ dbo ] . [ Task_Field ] ( [ TaskId ] [ uniqueidentifier ] NOT NULL , [ FieldId ] [ uniqueidentifier ] NOT NULL , CONSTRAINT [ PK_Task_Field ] PRIMARY KEY NONCLUSTERED ( [ TaskId ] ASC , [ FieldId ] ASC ) ) dbTask.Core_Field.Clear ( ) ; List < Core_Field > dbFields = _context.Core_Field .Where ( x = > fiel... | Inserting to a link table without fetching first |
C# | I have a tricky question . I 'm looking for the most concise , hackiest way of achieving the following : The result of which is all of the books in the library grouped by the first letter . Yadiyada is because my group object is not a simple string but an object.I 'm wondering if there 's a pure LINQ way of making it s... | query = ( from book in library.books.OrderBy ( x= > x.title ) group book by new { title = book.title [ 0 ] .ToString ( ) , yadiyada= '' '' } ) ; | Alphabetic GroupBy in Linq with a twist |
C# | Assume you have a LINQ query like I suppose in this case Select also runs in parallel execution mode . Maybe it 's just a cheap operation like i = > i*2 , so is there a way to stop parallel execution at a point of querying with chained methods ? ( maybe like .AsParallel ( ) .Where ( expensiveOp ) .AsSerial ? ( ) .Selec... | source.AsParallel ( ) .Where ( expensiveOperation ) .Select ( cheapOperation ) | Undo Enumerable.AsParallel ( ) , going back to serial mode |
C# | i am trying to get the main form of a process that i started , but the FromChildHandle and FromHandle always return null . the MainWindowHandle however is nonzero . | IntPtr p = process_wrapper.MainWindowHandle ; Form form = ( Form ) Control.FromChildHandle ( p ) ; if ( form ! = null ) { form.Close ( ) ; } | Getting the form of a childprocess |
C# | I am relatively new to LINQ and currently working on a query that combines grouping and sorting . I am going to start with an example here . Basically I have an arbitrary sequence of numbers represented as strings : I need to find all sNumbers in this list that contain a search pattern ( say `` 384 '' ) then return the... | List < string > sNumbers = new List < string > { `` 34521 '' , `` 38450 '' , `` 138477 '' , `` 38451 '' , `` 28384 '' , `` 13841 '' , `` 12345 '' } { `` 38450 '' , `` 38451 '' , `` 13841 '' , `` 28384 '' , `` 138477 '' } outputlist = ( from n in sNumbers where n.Contains ( searchPattern select n ) .ToList ( ) ; | LINQ query that combines grouping and sorting |
C# | I have recently come across a strange behavior with the dynamic keyword whilst I was testing something . This is n't a problem I desperately need solving as I was just experimenting , but I was wondering if anyone could shed any light on what was happeningI have a builder which returns an HttpWebRequest object and an e... | public class Program { public static void Main ( ) { dynamic dynamicString = `` { \ '' test\ '' : \ '' value\ '' } '' ; string json = `` { \ '' test\ '' : \ '' value\ '' } '' ; string test = new HttpWebRequestBuilder ( ) .SetRequestType ( ) //.SetBody ( json ) //uncomment this and it works .SetBody ( dynamicString ) //... | `` dynamic '' keyword with builder pattern hides extension method |
C# | I am trying to pass a type through to a method where I can check if it 'is ' a certain type . However the code I have below does not compile and I am wondering whats wrong . The compile error is : type or namespace name 'dataType ' could not be found . | public static List < object > findType ( Type dataType ) { List < object > items = new List < object > ( ) ; foreach ( KeyValuePair < int , object > entry in DataSource.ItemPairs ) { if ( entry.Value ! = null & & entry.Value is dataType ) { items.Add ( entry.Value ) ; } } return items ; } | How to use 'is ' when type passed in through method ? |
C# | I do n't want to reinvent the wheel : If I want to get every integer within a range of N from a given number , what is the most efficient way to do it ? What I mean is something like this : ... so that if the args passed in were 7 and 3 , the result would be 4..10 ; if the args passed in were 42 and 7 , the result woul... | public List < int > getIntsWithinN ( int BaseInt , int Offset ) List < int > listInts = new List < int > ( ) ; . . .Enumerable.Range ( lineNum - Offset , Offset * 2 + 1 ) .ToList ( listInts ) ; listInts = Enumerable.Range ( lineNum - Offset , Offset * 2 + 1 ) .ToList ( ) ; | Is there a preexisting function that will return a set of numbers based on a base number and an `` offset '' ? |
C# | I create a thread for each of my network communications and they add to a list responses whenever they hear back from a client . I 'm starting up the task below at execution to see if any communications come in . It displays the most recent one on screen.My question is ; is there a better way for me to do this ? It see... | Task task = new Task ( ( ( ) = > { int i = 0 ; while ( true ) { if ( responses.Count > i ) { Debug.WriteLine ( responses [ i ] ) ; int index = Form.ActiveForm.Controls.IndexOfKey ( `` responseBox '' ) ; Form.ActiveForm.Invoke ( ( MethodInvoker ) ( ( ) = > Form.ActiveForm.Controls [ index ] .Visible = true ) ) ; Form.Ac... | In C # ; what is the most efficent way to check for changes from a background thread ? |
C# | Note : This already works fine , but I 'm trying to understand Why it works this way , but not the other.I have a WinForm ( C # ) with dynamically put images , like so : Now if you click the 'Napred ' button , these images should be deleted ( among other things ) , for which I originally used : orNow if I run this , I ... | foreach ( Control ctrl in Controls ) if ( ctrl is PictureBox ) ctrl.Dispose ( ) ; for ( int i = 0 ; i < Controls.Count ; i++ ) if ( Controls [ i ] is PictureBox ) Controls [ i ] .Dispose ( ) ; for ( int i = Controls.Count - 1 ; i > = 0 ; i -- ) if ( Controls [ i ] is PictureBox ) Controls [ i ] .Dispose ( ) ; | Code confusion - why does one work , but not the other ? |
C# | The problem is as follows : My VS2015 solution has several projects , among them A and B.A is a regular project that contains a program/service/code that can translate certain source files into compiled resources ( with the idea being that the source is human-maintanable and under source control but the resulting resou... | + -- -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -+|Project A | |Assembly A || | + -- -- -- -- -- -- -- -- > | || | | |+ -- -- -- -- -- -- -- -- -- -+ + -- -- -- -+ -- -- -- -- -+ | | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + -- -- -- + | |+ -- -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -+|... | How to run a program from one of the projects in a solution as a build step ? |
C# | I suppose that this is an easy question but I could n't find the right answer . What means this syntax ? I 'm kind of confuse about the new ( ) at the end of the line : | public abstract class SomeClass < E > : Controller where E : ISomeInterface , new ( ) { //code of the abstract class } | What does this syntax mean in the declaration of an abstract class ? |
C# | I have two classes : Now I want to create this method : The point is – that I ca n't touch MyClass1 and MyClass2 so I ca n't make them use the same base . They are totally separated . Is any way to create this method somehow or I 'll have do duplicate it for each class ? | public class MyClass1 { public string AAAAA { get ; set ; } public string BBBBB { get ; set ; } public string CCCCC { get ; set ; } public string DDDDD { get ; set ; } } public class MyClass2 { public string AAAAA { get ; set ; } // same as MyClass1 public string BBBBB { get ; set ; } // same as MyClass1 public string ... | Create method on different class types |
C# | First , I do n't have much experience in .Net - especially within the last 7 years.I 'm trying to develop an application and would to incorporate another library ( https : //github.com/Giorgi/Math-Expression-Evaluator ) That library allows me to evaluate math expressions like Evaluate ( `` a+b '' , a : 1 , b : 1 ) . Th... | dynamic engine = new ExpressionEvaluator ( ) ; engine.Evaluate ( `` ( c+b ) *a '' , a : 6 , b : 4.5 , c : 2.6 ) ) ; if ( argument == null ) { return new Dictionary < string , decimal > ( ) ; } var argumentType = argument.GetType ( ) ; var properties = argumentType.GetProperties ( BindingFlags.Instance | BindingFlags.Pu... | Methods for dynamically creating an array in C # |
C# | In my database I have SQL , and C # I have , But the hash is different ? https : //dotnetfiddle.net/4bwAtm | DECLARE @ InputString nvarchar ( 15 ) ='pass'DECLARE @ InputSalt nvarchar ( 36 ) = 'FC94C37C-03A3-49A3-9B9F-D4A82E708618'DECLARE @ HashThis nvarchar ( 100 ) Declare @ BinaryHash varbinary ( max ) set @ HashThis = @ InputString + @ InputSaltset @ BinaryHash= HASHBYTES ( 'SHA1 ' , @ HashThis ) SELECT CAST ( N '' AS XML )... | Hash is different in SQL and C # ? |
C# | I 'm starting to see these statements and I am trying to wrap my head around these kind of statements . If I understand correctly we basically are casting obj into the variable car which would be a type `` SomeAuto '' ? 1 ) What is the official terminology of this statement ? 2 ) What would happen if I wanted to change... | if ( obj is SomeAuto car ) { //Do stuff } | What does this syntax do ? if ( obj is SomeType obj2 ) |
C# | I 've created a little bit of code which adds data from Linq.Tables ( dc.GTMD_Financials ) to a UserControl . For every entry in the database it shows a new usercontrol.But i would like to use this code in a method to reuse it throughout the application . My problem is that each time i call the method i would like to u... | int locationControl = 78 ; DataClasses1DataContext dc = new DataClasses1DataContext ( ) ; dc.GTMD_Financials.ToList ( ) .ForEach ( x = > { KPIEntrys uc = new KPIEntrys ( ) ; // UserControl uc.KPI = x.KPI ; // Add data to properties uc.Status = x.Status.ToString ( ) ; uc.Goal = x.Goal.ToString ( ) ; uc.Currently = x.Cur... | Multiple Linq.Tables in method |
C# | I understand that variable capturing is done by the compiler and not by the classes in the .NET framework itself . However , when the DLR was introduced , some of this work must surely have needed to have been done within the framework so as to defer it to runtime.For e.g. , in the piece of code given below : The type ... | dynamic d = ... Func < int , bool > func = n = > n > d ; | Which is the code that creates captured variables / closures ? |
C# | I have an item processing application , and I want to process a number of items in parallel . But , it appears sometimes it does n't process one item at all , and sometimes it processes more than once . My code belowOn a timer tick , a new thread is created which prepares an item list from database , then locks every i... | SqlConnection connection = GetConnection ( ) ; string selectCommand = my_select_command_where_IsLocked_is_null ; List < Item > itemList = new List < Item > ( ) ; using ( SqlDataAdapter adapter = new SqlDataAdapter ( selectCommand , connection ) ) { using ( SqlCommandBuilder cbCommandBuilder = new SqlCommandBuilder ( ad... | C # multithreading some threads seems to not run |
C# | I was playing around with using an lvalue as a result of conditional operator ( cond ? expr1 : expr2 ) .Consider following exampleNow , I would suspect , based on value of condition , that either v1 or v2 gets incremented . That actually is the case , as long as Value ( ( 1 ) ) is class . Once I change it to struct , i... | class /* ( 1 ) */ Value { public int MagicNumber { get ; private set ; } = 0 ; public void Increment ( ) { /* magical code , that modifies MagicNumber */ } } void Main ( ) { Value v1 , v2 ; /* ( 2 ) */ bool condition = /* ... */ ; ( condition ? v1 : v2 ) .Increment ( ) ; // ( 3 ) } ( condition ? v1 : v2 ) .Increment ( ... | Reference semantics of conditional operator |
C# | Quite simply , why does this code fail to compile ? Since every T implements IWorld , every instance of Foo < T > should match Foo < IWorld > . Why not ? Is there any way around this ? I really do n't want to resort to generics to accomplish this . | public interface IWorld { } public class Foo < T > where T : IWorld { } public void Hello < T > ( T t ) where T : IWorld { Foo < IWorld > bar1 = new Foo < T > ( ) ; //fails implicit cast Foo < IWorld > bar2 = ( Foo < IWorld > ) new Foo < T > ( ) ; //fails explicit cast } | Casting constrained generic class in C # |
C# | I have an XML file : I also have an object : And here is the code that I use to read the data into memory : But it would not let me do that . When the LINQ statement is executed , the default constructor is called on the TestItem object , and then I get the null exception because item.Element ( ns + `` Question '' ) .V... | < ? xml version= '' 1.0 '' encoding= '' us-ascii '' ? > < TestItems xmlns= '' http : //www.blogger.com '' > < TestItem correct= '' 0 '' incorrect= '' 0 '' > < Question > question < /Question > < Answer > answer < /Answer > < Tags > test1 ; test2 < /Tags > < /TestItem > < TestItem correct= '' 0 '' incorrect= '' 0 '' > <... | Ca n't read from xml into an < > using linq , get nulls |
C# | If you have a method or type Foo < T > , then the CLR may compile multiple versions for different T. I know that all reference types share the same version . How does it work for structs ? Is code sometimes shared , or never shared , for different structs ? I could imagine that code is shared for all structs of the sam... | interface IBar { void DoBar ( ) ; } struct Baz : IBar { public void DoBar ( ) { ... } } struct Quux : IBar { public void DoBar ( ) { ... } } public void ExecuteBar < T > ( T bar ) where T : IBar { bar.DoBar ( ) ; } ExecuteBar ( new Baz ( ) ) ; ExecuteBar ( new Quux ( ) ) ; | When is code shared for different instantiations of generics in the CLR ? |
C# | Knowing RedirectToAction , I was looking for something similar to keep the URL stable for the user and still pass responsibility from one action to another.Since I found zero Google results on this topic , I might as well completely try to solve an XY problem.Still , I 'll try to explain why I believe there might be a ... | public ActionResult A ( int id ) { var uniqueID = CalculateUniqueFromId ( id ) ; // This compiles . return RedirectToAction ( `` B '' , new { uniqueID } ) ; // This does not compile . return RewriteToAction ( `` B '' , new { uniqueID } ) ; } public ActionResult B ( Guid uniqueID ) { var model = DoCreateModelForUnique (... | Is there something like `` RewriteToAction '' ? |
C# | I have an application that was written for remote trucks to use on cell service . Before I do anything , I am checking the internet with this class : In some cases , the light on the external cellular device has a green light as if it has internet . My test class comes back false so it thinks it does not have internet.... | using System.Net ; namespace SSS.ServicesConfig.MiscClasses { public class VerifyInternetAccess { public static bool HasInternet ( ) { try { using ( var client = new WebClient ( ) ) using ( var stream = client.OpenRead ( `` http : //www.google.com '' ) ) { return true ; } } catch { return false ; } } } } | testing internet connection on a cellular network |
C# | Does anyone know why this code does n't compile ? I realize Nullable has a constraint But Nullable is struct . I also know this constraint has a restriction `` The type argument must be a value type . Any value type except Nullable can be specified . '' ( https : //docs.microsoft.com/en-us/dotnet/csharp/programming-gui... | Nullable < Nullable < int > > n = null ; where T : struct | Nullable restrictions |
C# | I have a custom control that consists of a filled rounded rectangle with text . ( The actual control is more complicated but the code shown here has the sames symptoms . ) I attached instances of the control to a Panel , and made that Panel a child of another Panel with AutoScroll = true . I thought that would be enoug... | using System ; using System.Drawing ; using System.Drawing.Drawing2D ; using System.Windows.Forms ; namespace CustomControlScrollTest { static class Program { [ STAThread ] static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new Form1 (... | Allow custom control to correctly scroll out of view |
C# | Sorry for the vague title , but I was n't sure how to summarize this in one phrase . I have a situation with a lot of redundant C # code , and it really looks like some kind of crafty trick using some property of inheritance or generics would solve this . However , I 'm not a terribly experienced programmer ( particula... | public class Foo : SuperFoo { ... public Foo SomeMethod ( ) { ... } } public class Bar : SuperFoo { ... public Bar SomeMethod ( ) { ... } } public class Baz : SuperFoo { ... public Baz SomeMethod ( ) { ... } } ... public class SuperFoo { ... } public void SomeEventHasHappened ( ... ) { ProcessFoos ( ) ; ProcessBars ( )... | Having trouble getting rid of redundant code via inheritance or generics |
C# | I need some help writing a LINQ query where I am trying to do some `` conditional/composite '' grouping . ( Not sure that is the right term ) . Let me explain.If I have the following classes : From this lets say I have these Objects : From this I want to create a query that groups by - > SupervisorId - > CountryId - > ... | class Device { int Id ; string DeviceType ; string DeeviceValue ; } class Employee { int Id ; int SupervisorId ; int CountryId ; List < Device > Devices = new List < Device > ( ) ; } List < Employee > Employees = new List < Employee > ( ) ; var emp1 = new Employee ( ) ; emp1.Id = 1 ; emp1.CountryId = 1 ; emp1.Superviso... | c # linq nested `` conditional/composite '' grouping |
C# | I 'm using C # Web-Api with Owin , hosted as a Windows Service , to expose card reader utility.I 'm trying to use Server Sent Events . The client sends a request to open the stream , and I want to do logic when it closes ( i.e the user closes the browser , or calls eventSource.close ( ) ) It looks like that : When test... | public class CardReaderController : ApiController { static ConcurrentDictionary < int , Connection > connections = new ConcurrentDictionary < int , Connection > ( ) ; static CardReader cardReader = CardReader.Instance ; CardReaderController ( ) { cardReader.OnCardRead += OnCardRead ; } static void OnDisconnect ( int id... | OWIN web api CancellationToken not being called |
C# | By default for URL routing in MVC is { controller } / { action } / { id } . Then we can access mydomain.com/Products/Details/1 and etc.Now , I have register another map route I called CategoryLandingPage.So it will show all the category in the page . Then I register another map route called CategoryDetailsWhen somebody... | routes.MapRoute ( name : `` CategoryLandingPage '' , url : `` category '' , defaults : new { controller = `` Category '' , action = `` Index '' } ) ; routes.MapRoute ( name : `` CategoryDetails '' , url : `` category/ { categoryName } '' , defaults : new { controller = `` Category '' , action = `` Details '' , category... | Routing wrong access the action |
C# | Well , my titling is a bit weird I guess . But let me explain my question.I have a while loopIt would be neat when GetObj ( ) is n't called twice per loop.I 've debugged it in another project to be sure that .NET do not avoid calling the method twice . But that is n't the case . My actual question now isIs there a simp... | while ( GetObj ( ) == null || ! GetObj ( ) .Initialized ) { doStuff ( ) ; } | How to use single result in While Loop ? |
C# | I 've got a few huge xml files , 1+ gb . I need to do some filtering operations with them . The easiest idea I 've come up with is to save them as txt and ReadAllText from them , and start doing some operations like The moment I try to do that , however , the program crashes out of memory . I 've looked at my task mana... | var a = File.ReadAllText ( `` file path '' ) ; a = a.Replace ( `` < `` , `` \r\n < `` ) ; | How to get around OutOfMemory exception in C # ? |
C# | I have a following set of numbers : Now , I need to group the data by the first value in a way that no group key is present in the group values . So , for instance , if I were to simply group data , I 'd get this result:46 here is a group key in the third group and a group value in the second group . In this case I nee... | 1 1371 14311 3711 4611 13246 6546 13969 90 1 137 14311 37 46 13246 65 13969 90 1 137 14311 37 46 132 65 13969 90 | Group data having unique keys and values |
C# | Suppose I use MemoryMarshal.CreateSpan to access the bytes of a local value type , for example the following ( not very useful ) code : While this code works as intended , is the indicated check guaranteed to survive compilation to IL and JIT compilation , without being optimised to true , given that the variable value... | using System ; using System.Runtime.InteropServices ; // namespace and class boilerplate go hereprivate static void Main ( ) { int value = 0 ; Span < byte > valueBytes = MemoryMarshal.AsBytes ( MemoryMarshal.CreateSpan ( ref value , 1 ) ) ; var random = new Random ( ) ; while ( value > = 0 ) // the check in question { ... | Can optimised builds and JIT compilation create problems when modifying a variable through a Span < T > ? |
C# | I 'm stuck with arrays and need some help.I have two arrays and I 'm comparing it using foreach loop . I want the program to write `` you won '' ONLY if there are two numbers in winningNumbers that matches with someNumbers . If there is only one match , the output should be `` You lost '' ( I have to use loops to solve... | int [ ] someNumbers = { 1 , 2 , 3 , 4 , 5 , 6 } ; int [ ] winningNumbers = { 1 , 2 , 13 , 14 , 15 , 16 } ; bool winning = false ; foreach ( var item1 in someNumbers ) { foreach ( var item2 in winningNumbers ) { if ( item1 == item2 ) { winning = true ; } } } if ( winning == true ) { Console.WriteLine ( `` You won '' ) ;... | comparing two arrays with only loops |
C# | I would like a clean/compact pattern that is exception safe and will properly dispose rulesKey , even if something has thrown . This does not appear to be possible with using ( unless maybe 4 usings but that seems so verbose and opening extra resources that I might not even need opened ) . What gets me is that this wou... | { RegistryKey rulesKey = null ; rulesKey = rulesKey ? ? Registry.LocalMachine.OpenSubKey ( `` Software\\Wow6432Node\\Company\\Internal\\Product '' ) ; rulesKey = rulesKey ? ? Registry.LocalMachine.OpenSubKey ( `` Software\\Company\\Company\\Internal\\Product '' ) ; rulesKey = rulesKey ? ? Registry.LocalMachine.OpenSubK... | C # : Is there a clean pattern for finding the right object combined with using ? |
C# | I 'm new to xUnit , but , as far as I know , the standard way of checking whether something throws an exception is to use Assert.Throws < T > or Assert.ThrowsAny < T > methods.But these methods expect an Action as parameter ; and ref structs ca n't be `` embedded '' in lambdas.So , how does one test whether a given met... | [ Fact ] public void HelpMe ( ) { var pls = new Span < byte > ( ) ; Assert.ThrowsAny < Exception > ( ( ) = > { plsExplode = pls [ -1 ] ; } ) ; } | How to test whether a ref struct method is throwing an exception using xUnit ? |
C# | So , this is my class : And this is how my JSON-String looks like : I would like to get a User [ ] users out of it.My Problem is the { `` results : '' : [ ... . ] } -Part.I 've tried it this way : but I think the results-Part is messing everything up somehow.What would be the best way to solve this problem ? | public class User { public User ( ) { } public string Username { get ; set ; } public string Password { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } { `` results '' : [ { `` FirstName '' : '' firstname1 '' , '' LastName '' : '' lastname1 '' , '' Password '' : '' TestPas... | Get C # -Object-Array out of a JSON-String |
C# | I 'm writing a socket server which should handle every message received from every client connected to it.All the messages are enqueued in an observable , so it can be subscribed and observed outside.To ensure that all client socket messages are put on the same observable I 've used the following snippet : Now , I 've ... | private Subject < IObservable < Msg > > _msgSubject ; public IObservable < Msg > Messages { get ; private set ; } public SocketServer ( ) { // ... // Initialization of server socket // ... _msgSubject = new Subject < IObservable < Msg > > ( ) ; Messages = _msgSubject.Merge ( ) ; } private void OnNewConnection ( ISocket... | Disposing combined observables from events |
C# | I have implemented a deep clone method using a copy constructor in C # . To verify that it works , I am testing it by comparing the results of serializing an object and it 's clone . The serialization is done in terms of a generic object T. I have also tried it in terms of a concrete object and get the same results.I h... | private byte [ ] ObjectToBytes ( T obj ) { BinaryFormatter formatter = new BinaryFormatter ( ) ; using ( MemoryStream stream = new MemoryStream ( ) ) { formatter.Serialize ( stream , obj ) ; stream.Seek ( 0 , SeekOrigin.Begin ) ; return stream.ToArray ( ) ; } } T original = this.GetNewThing ( ) ; T clone = original.Dee... | Serialization modifying contents of original object in C # |
C# | i want to update the user information on database im using c # .here is my code , it doesnt work and it does n't give me any errors . | protected void Page_Load ( object sender , EventArgs e ) { lbldisplay.Text = `` < b > < font color=BLUE > '' + `` WELLCOME : : `` + `` < /font > '' + `` < b > < font color=white > '' + Session [ `` Name '' ] + `` < /font > '' ; SqlConnection con = new SqlConnection ( `` Data Source=STUDENT-PC ; Initial Catalog=webservi... | Updating information in database |
C# | I try to capture desktop screenshot using SharpDX . My application is able to capture screenshot but without labels in Windows Explorer.I tryed 2 solutions but without change . I tried find in documentation any information , but without change.Here is mi code : | public void SCR ( ) { uint numAdapter = 0 ; // # of graphics card adapter uint numOutput = 0 ; // # of output device ( i.e . monitor ) // create device and factory var device = new SharpDX.Direct3D11.Device ( SharpDX.Direct3D.DriverType.Hardware ) ; var factory = new Factory1 ( ) ; // creating CPU-accessible texture re... | FileLabels are not visible |
C# | I have a text like this : Could anyone tell me how to pick the per part from it . I know how to pick the $ amount . It 's like this : Any help would be highly appreciated . | my text has $ 1 per Lap to someone . new Regex ( @ '' \ $ \d+ ( ? : \.\d+ ) ? `` ) .Match ( s.Comment1 ) .Groups [ 0 ] .ToString ( ) | Regex to pick a part of a word |
C# | I have a list . I 'd like to take the last value from each run of similar elements . What do I mean ? Let me give a simple example . Given the list of words [ 'golf ' , 'hip ' , 'hop ' , 'hotel ' , 'grass ' , 'world ' , 'wee ' ] And the similarity function 'starting with the same letter ' , the function would return th... | > var words = new List < string > { `` golf '' , `` hip '' , `` hop '' , `` hotel '' , `` grass '' , `` world '' , `` wee '' } ; > words.LastDistinct ( x = > x [ 0 ] ) [ `` golf '' , `` hotel '' , `` grass '' , `` wee '' ] | How to select last value from each run of similar items ? |
C# | I have the following methods : I do n't want to wait for the result of an already running operation.I want to return _cachedData and update it after the Task will finish.How to do this ? I 'm using .net framework 4.5.2 | public int getData ( ) { return 2 ; } // suppose it is slow and takes 20 sec// pseudocodepublic int GetPreviousData ( ) { Task < int > t = new Task < int > ( ( ) = > getData ( ) ) ; return _cachedData ; // some previous value _cachedData = t.Result ; // _cachedData == 2 } | How to return the result from Task ? |
C# | I have 2 bool flags and need to filter my collection accordingly . There has to be an cleaner way to do this . If anyone can point me in the right direction I 'd appreciate it . Thanks . | var _filteredEvents = from ev in _events select ev ; if ( ! queueEmail ) // do n't queue email { if ( ! queueTextMessaging ) // do n't queue textmessaging { _filteredEvents = from ev in _events where ev.QueueTypeEnumText ! = QueueType.TextMessage.ToString ( ) & & ev.QueueTypeEnumText ! =QueueType.Email.ToString ( ) sel... | Is there a way to simplify this linq |
C# | I need to add a scroll bar for a component when a user changes their font size to 125 % or 150 % . To do this I added a method in the component , which sets the AutoScroll property to true.This works well , but one of the components should not get a scrollbar.The above method will be triggered when initializing the con... | protected override void OnSizeChanged ( EventArgs e ) { if ( SystemFonts.DefaultFont.Size < 8 ) { this.AutoScroll = true ; } if ( this.Handle ! = null ) { this.BeginInvoke ( ( MethodInvoker ) delegate { base.OnSizeChanged ( e ) ; } ) ; } } this.ultraExpandableGroupBoxPanel1.Controls.Add ( this.pnlViewMode ) ; this.ultr... | How could I change the properties of a Control after the resource file has been applied ? |
C# | I am working on a website ( developed in ASP.NET with C # ) that was passed on to me . As I 'm working through the site , I notice much of the site has this type of code in it : This is all typically done in the code-behind of the site ( in the Page_Load method ) . Essentially , this was put in place to prevent a non-l... | EmailLabel.Visible = false ; WhateverButton.Visible = false ; AnotherControl.Visible = false ; ... | Hiding Controls as a Form of Web Security , Suggestions for Better ? |
C# | I have an integer u=101057541.Binary , this is equal to : 00000110 00000110 00000100 00000101Now , I regard each byte as a seperate decimal ( so 6 , 6 , 4 , 5 in this case ) .I want to subtract -1 from the first byte , resulting in 6-1=5.I try to do this as follows : However , the result is the same as when I ADD 1 to ... | int West = u | ( ( ( u > > 24 ) - 1 ) < < 24 ) ; | How to do -1 on a specific byte of an integer in C # ? |
C# | This prints `` Generic '' . Removing , EnumTest t = EnumTest.EnumEntry makes it print `` Normal '' .And yet the standard appears to be pretty clear , from 14.4.2.2 Better function member the first discriminator to be applied is : If one of MP and MQ is non-generic , but the other is generic , then the non-generic is be... | public enum EnumTest { EnumEntry } public class TestClass { public string FunctionMember ( string s , EnumTest t = EnumTest.EnumEntry ) { return `` Normal '' ; } public string FunctionMember < T > ( T t ) { return `` Generic '' ; } } class Program { static void Main ( string [ ] args ) { TestClass t = new TestClass ( )... | Why is a generic function member chosen over a non-generic one ? |
C# | I have a specific pattern with the following formatUsing this code I get the following resultI want to split number from $ ( ) . i.e . expected result isHow can I achieve this ? | string exp = `` $ ( 2.1 ) + $ ( 3.2 ) -tan ( $ ( 23.2 ) ) * 0.5 '' ; var doubleArray = Regex .Split ( str , @ '' [ ^0-9\ . ] + '' ) .Where ( c = > c ! = `` . '' & & c.Trim ( ) ! = `` '' ) .ToList ( ) ; //result [ 2.1,3.2,23.2,0.5 ] [ 2.1,3.2,23.2 ] | How to split a number from a regex expression in c # ? |
C# | I have the following class : I then made a list of vehicles like : Next I was trying to get a list of DatesManufactured and for each date the vehicles that were manufactured on that date.So I went for : This works fines but I 'm not sure about the x.First ( ) part . It works but it does n't feel quite right . Does anyb... | public class Vehicle { public string Make { get ; set ; } public DateTime DateManufactured { get ; set ; } } var dateTime1 = DateTime.Now.AddDays ( -7 ) ; var dateTime2 = DateTime.Now.AddDays ( -8 ) ; var dateTime3 = DateTime.Now.AddDays ( -9 ) ; var vehicles = new List < Vehicle > { new Vehicle { Make = `` Ferrari '' ... | Is there a better way to set a property common to a list of items in linq |
C# | I 'm write this code for run sql server script : but this line : i get this error : what reference should be add to the project ? | string sqlConnectionString = `` Data Source= . ; Initial Catalog=behzad ; Integrated Security=True '' ; //string sqlConnectionString = `` Data Source= ( local ) ; Initial Catalog=AdventureWorks ; Integrated Security=True '' ; FileInfo file = new FileInfo ( `` d : \\behzadBULK.sql '' ) ; string script = file.OpenText ( ... | How can i run sql server script with c # ? |
C# | I am parsing string time in date using DateTime.Parse method . It parses properly and returns me today 's date with the entered time . But I am not able to determine the timezone when it takes the date part . Is it considering local date or UTC date ? On referring official documentation of DateTime.Parse , it is mentio... | public class Program { public static void Main ( string [ ] args ) { //Your code goes here Console.WriteLine ( DateTime.Parse ( `` 4:00 '' ) ) ; //prints 09.05.2019 04:00:00 - here did it take 09.05.2019 from local timezone or is it UTC ? } } | ` DateTime.Parse ` parses the timestamp in which timezone ? |
C# | I am building a form and I have to keep using an inline conditional to add a readonly html attribute : You ca n't use a conditional for just the @ readonly property 's value because even if it is set to null , it will be rendered out to the client as readonly= '' '' and that is enough for a browser to make that field r... | @ Html.LabelFor ( model = > model.EventDate ) < div class= '' row '' > < div class= '' col-xs-3 '' > @ Html.EditorFor ( model = > model.EventDate , new { htmlAttributes = Model.IsEditorReadOnly ? ( object ) new { @ class = `` form-control input-lg '' , @ type = `` date '' , @ readonly = `` readonly '' } : ( object ) ne... | How do I avoid repetitive inline conditionals for defining htmlAttributes of Html.EditorFor ( ) |
C# | I have a linq query which iterates over hundreds of XML elements to count the quantity of specific tools used in a collection of tools.However , the qty element in the tools xelement collection , which should contain a number , occasionally contains text such as `` As required '' as opposed to a specific number . This ... | Dictionary < int , int > dict = listTools.Descendants ( `` tool '' ) .GroupBy ( x = > ( int ) x.Element ( `` id '' ) , y = > ( int ) y.Element ( `` qty '' ) ) .ToDictionary ( x = > x.Key , y = > y.Sum ( ) ) ; | How do I ignore/remove non-number values from linq query results C # |
C# | I do n't understand how a compiler can be smart enough to construct an O ( 1 ) lookup for MyObject where I can put anything insideI understand how this can be done for a limited number of non-primitives such as but how can it possibly know how to do this for any implementation of MyObject ? | public class MyObject { // ... } public class MyObject { int i { get ; set ; } char c { get ; set ; } } | How are .NET compilers able to construct O ( 1 ) lookups for any T in a HashSet < T > ? |
C# | The request : I 'd like to be able to write an analyzer that can provide a proxy value for a certain expression and trigger a re-parsing of the document.The motivation : Our code is littered with ABTests that can be either in a deployed or active state with a control and variant group . Determining a test 's state is d... | if ( ExperimentService.IsInVariant ( ABTest.Test1 ) ) { } if ( ! ExperimentService.IsInVariant ( ABTest.Test1 ) ) if ( ExperimentService.IsInVariant ( ABTest.Test1 ) || true ) var val = ... .. & & ( ExperimentService.IsInVariant ( ABTest.Test1 ) ; if ( val ) { // val is always going to be false if we deployed control .... | How to rewrite AST dynamically in resharper plugin ? |
C# | Let 's say I have : Is there a built-in method in .NET that will let me get the properties and values for variable i of type Item that might look like this : I know that .ToString ( ) can be overloaded to provide this functionaility , but I could n't remember if this was already provided in .NET . | public class Item { public string SKU { get ; set ; } public string Description { get ; set ; } } ... . { SKU : `` 123-4556 '' , Description : `` Millennial Radio Classic '' } | Is there a built-in .NET method for getting all of the properties and values for an object ? |
C# | We came across an issue recently with F # code calling into C # code . I have simplified the issue down as simple as I can . The C # code is as follows : The F # code needs to call the ConfigurationBuilders DoWork function . Note that the DoWork function takes two parameters , a simple string and a Func as a second par... | using System ; namespace CSharpLib { public abstract class InputMessageParent { public readonly Guid Id ; protected InputMessageParent ( Guid id ) { this.Id = id ; } } public class Result { public string ResultString ; } public enum FunctionResult { None , Good , Bad } public class ConfigurationBuilder { public Result ... | F # code invoking a c # method containing a Func parameter behaving strangely |
C# | Is there a good way to deal with this type of situation to ensure that disposible instances inside the class get called ? ( There is no signal to callers that they must call 'Close ' except in documentation . ) Implementations of IMyInterface do not necessarily encapsulate IDisposible instances and are closed and reope... | interface IMyInterace { void Open ( ) ; object Read ( ) ; void Close ( ) ; } class MyImplementation : IMyInterface { public void Open ( ) { /* instantiates disposible class */ } // ... public void Close ( ) { /* calls .Dispose ( ) ; */ } } | How to deal with a class than encapsulates a disposible instance ? |
C# | My logged stack trace seems to be missing a step.Why has the stack trace gone straight from StartLoadingResources to Insert ( missing the Add step ) ? The code is compiled as Debug , with `` Optimize code '' in Build options left unchecked . | private void StartLoadingResources ( DataService separateDataService ) { ... batchResource.Resources.Add ( key , new List < string > ( ) ) ; // batchResource.Resources is the Dictionary object involved ... } System.AggregateException : One or more errors occurred . -- - > System.ArgumentException : An item with the sam... | Why is my stack trace missing steps ? |
C# | Let me explain what I mean : I have a database that contains 4 columns , one of which is Letter , so each row has a character from ' A ' to ' Z ' , and these are n't unique , so there are multiple rows with ' A ' , multiple rows with ' B ' etc . What I want to do is get 26 ( a-z ) rows with ALL letters , but randomize ... | var randomQuestions = questions.Distinct ( ) .GroupBy ( q = > q.Letter ) .Take ( 26 ) .ToArray ( ) ; | How to get array of random A-Z letters ? |
C# | Parameter arrays allow a variable number of arguments to be passed into a method : But I fail to see their usefulness , since same result could be achieved by specifying a parameter of particular array type : So what benefits ( if any ) does parameter array have over value parameter of array type ? thank you | static void Method ( params int [ ] array ) { } static void Method ( int [ ] array ) { } | I do n't understand the usefulness of parameter arrays ? |
C# | Let 's say I have an interface that many many distinct classes implement : ( Note : I ca n't make it an abstract base class as implementors of IHaveObjects may already have a base class . ) Now I want to add a new method to the interface , so that one implementer of the interface can have special behaviour for it . Ide... | public interface IHaveObjects { object firstObject ( ) ; } public interface IHaveObjects { object firstObject ( ) ; object firstObjectOrFallback ( ) { return firstObject ( ) ; } } public class ObjectHaverPlus : IHaveObjects { public override object IHaveObjects.firstObjectOrFallback ( ) { return firstObject ( ) ? ? get... | Workaround for being unable to put code in interfaces |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.