lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have many hours thinking how i can solve , this is my funtion : This function split a string in parts of 36 characters then add the resultant characters with spaces for make a centered text : For example : Result : Line1 and Line2 are correct but i dont need the Line3 , how i can prevent to print this unnecessary lin... | private String TextAlignCenter ( String Line ) { String CenterLine = String.Empty ; if ( Line.Length > 36 ) { for ( int i = 0 ; i < Line.Length ; i += 36 ) { if ( ( i + 36 ) < Line.Length ) TextAlignCenter ( Line.Substring ( i , 36 ) ) ; else TextAlignCenter ( Line.Substring ( i ) ) ; } } else { Int32 CountLineSpaces =... | Center and Split string with maxchar |
C# | So Inversion Of Control is a vague description , so Dependency Injection became the new definition . This is a very , very powerful solution and is quite possibly just as confusing to someone whom has never encountered it.So in my quest to not be a deer in headlights , I read up . I found several terrific books and onl... | public interface ISiteParameter { Guid CustomerId { get ; set ; } string FirstName { get ; set ; } string LastName { get ; set ; } string Phone { get ; set ; } } public interface IInjectSiteParameter { void InjectSite ( ISiteParameter dependant ) ; } public class SiteContent : IInjectSiteParameter { private ISiteParame... | The Five W 's of DI , IoC because it is making my brain explode |
C# | The following returns trueso doesThe RegEx is in SingleLine mode by default , so $ should not match \n . \n is not an allowed character.This is to match a single ASCII PascalCaseWord ( yes , it will match a trailing Cap ) Does n't work with any combinations of RegexOptions.Multiline | RegexOptions.SinglelineWhat am I d... | Regex.IsMatch ( `` FooBar\n '' , `` ^ ( [ A-Z ] ( [ a-z ] [ A-Z ] ? ) + ) $ '' ) ; Regex.IsMatch ( `` FooBar\n '' , `` ^ [ A-Z ] ( [ a-z ] [ A-Z ] ? ) + $ '' ) ; | C # System.RegEx matches LF when it should not |
C# | Really simple to replicate , the output is bizarre ; Expected output is `` bbb bbb '' Actual output is `` aaa bbb '' Has anyone got any MSDN explanation of this behaviour ? I could n't find any . | ( ( a ) new b ( ) ) .test ( ) ; new b ( ) .test ( ) ; public class a { public virtual void test ( string bob = `` aaa `` ) { throw new NotImplementedException ( ) ; } } public class b : a { public override void test ( string bob = `` bbb `` ) { HttpContext.Current.Response.Write ( bob ) ; } } | Overriding default parameters in C # |
C# | I have the following scenario/requirement : I have two tasks , task A and task B , which both return the same type of data.If task A , upon completion , has data in its result , I need to return the result of Task A - otherwise I return the result of task B.I 'm trying to performance optimize this for parallellism and ... | var firstSuccessfulTask = await Task.WhenAny ( taskA , taskB ) ; if ( firstSuccessfulTask ! = taskA ) { await taskA ; } if ( taskA.Result ! = null ) { return taskA.Result ; } return await taskB ; | C # async/await - multiple tasks with one preferred |
C# | I have a class that expects an IWorkspace to be created : and a derived class Derived . In this derived class I have a copy-constrcutor that should create an instance of Derived based on an instance of MyClass . The above won´t compile with following error : Can not access protected member MyClass.workspace ' via a qua... | public class MyClass { protected IWorkspace workspace ; public MyClass ( IWorkspace w ) { this.workspace = w ; } } public class Derived : MyClass { public Derived ( MyClass m ) : base ( m.workspace ) { } } | Create a constructor that does not exist in base class |
C# | In my program , I ran into a problem writing a small number to a context.Response that is then being read by a jQuery ajax response.returns [ object XMLDocument ] However , returns 0.00 as expected.Using `` n '' is perfectly fine for my program , but why did `` # . # '' return with an XMLDocument ? | value = -0.00000015928321772662457 ; context.Response.Write ( value.ToString ( `` # . # '' ) ) ; context.Response.Write ( value.ToString ( `` n '' ) ) ; | Why does n't # . # work for very small numbers ? |
C# | I feel like I 'm stuck between several bad solutions here and need some advice on how to minimize future agony . We are using Massive ORM , which in its constructor has these lines : The important part for me here is that it reads the connection strings from ConfigurationManager . We are trying to centralize configurat... | var _providerName = `` System.Data.SqlClient '' ; if ( ConfigurationManager.ConnectionStrings [ connectionStringName ] .ProviderName ! = null ) _providerName = ConfigurationManager.ConnectionStrings [ connectionStringName ] .ProviderName ; _factory = DbProviderFactories.GetFactory ( _providerName ) ; ConnectionString =... | Least-bad way to change constructor behaviour |
C# | Is there any essential difference between this code : and this ? Or does the first invoke the method on the current thread while the second invokes it on a new thread ? | ThreadStart starter = new ThreadStart ( SomeMethod ) ; starter.Invoke ( ) ; ThreadStart starter = new ThreadStart ( SomeMethod ) ; Thread th = new Thread ( starter ) ; th.Start ( ) ; | .NET threading question |
C# | I 've got an Application which consists of 2 parts at the momentA Viewer that receives data from a database using EFA Service that manipulates data from the database at runtime.The logic behind the scenes includes some projects such as repositories - data access is realized with a unit of work . The Viewer itself is a ... | public IEnumerable < Request > GetAllUnResolvedRequests ( ) { return AccessContext.Requests.Where ( o = > ! o.IsResolved ) ; } var requests = AccessContext.Requests.Where ( o = > o.Date > = fromDate & & o.Date < = toDate ) .ToList ( ) ; foreach ( var request in requests ) { AccessContext.Entry ( request ) .Reload ( ) ;... | How to ... Display Data from Database |
C# | doing a little experimenting to find out how things work . I have the following code ... I 'm wondering why MethodTest receives the int 20 almost always ( unless I 'm stepping through in debugger ) .Obviously there 's something missing in my understanding as I assumed that when ' i ' is passed it would be part of a man... | for ( int i = 0 ; i < 20 ; i++ ) { Task.Factory.StartNew ( ( ) = > MethodTest ( i ) ) ; } | Private variables in .net 4.0 tasks |
C# | Update : check out the example at the bottomI need to message between classes . The publisher will loop indefinitely , call some method to get data , and then pass the result of that call into OnNext . There can be many subscribers , but there should only ever be one IObservable , and one long-running task . Here is an... | using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Diagnostics ; using System.Reactive.Linq ; using System.Reactive.Subjects ; using System.Threading.Tasks ; namespace UnitTestProject1 { [ TestClass ] public class UnitTest1 { private static string GetSomeData ( ) = > `` Hi '' ; [ TestMetho... | How to Separate IObservable and IObserver |
C# | When you have some property that 's like : then compile and later change it to : it seems like the compiled code is different between the two assemblies , which I could see using the Reflector.Why does the compiler differentiates between the two code ? Is n't it only necessary to see if there is any ambiguous type at c... | using Algebra ; public Algebra.Vector3 Direction { get { return this.direction ; } } using Algebra ; public Vector3 Direction { get { return this.direction ; } } | Why does the C # compiler differentiates between these 2 cases ? |
C# | Straight to the point : I get a very related question which actually deals on why does i.ToString ( ) work fine.Edit : Just found out this corner case has been the most voted one in this SO thread ! | int ? i = null ; i.ToString ( ) ; //happyi.GetType ( ) ; //not happy | Why does some methods work while some do not on null values of nullable structs ? |
C# | I wrote a tool that generates a C # source file containing the results of a processor intensive computation ( precomputing the result speeds up the startup time of my application by roughly 15 minutes ) . It is a byte [ ] that looks sorta like this : I 'm wondering though , are there hidden costs for hardcoding the res... | public static byte [ ] precomputedData = new byte [ ] { 0x01,0x02,0x03,0x04,0x05,0x06,0x07 , 0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E , 0x0F,0x10 , ... . continue for 8000 more lines ... . | Are there hidden expenses hardcoding data as code in C # ? |
C# | I need to calculate distances between every pair of points in an array and only want to do that once per pair . Is what I 've come up with efficient enough or is there a better way ? Here 's an example , along with a visual to explain what I 'm trying to obtain : e.g. , first get segments A-B , A-C , A-D ; then B-C , B... | var pointsArray = new Point [ 4 ] ; pointsArray [ 0 ] = new Point ( 0 , 0 ) ; pointsArray [ 1 ] = new Point ( 10 , 0 ) ; pointsArray [ 2 ] = new Point ( 10 , 10 ) ; pointsArray [ 3 ] = new Point ( 0 , 10 ) ; // using ( n * ( n-1 ) ) / 2 to determine array sizeint distArraySize = ( pointsArray.Length* ( pointsArray.Leng... | What is the most efficient way to avoid duplicate operations in a C # array ? |
C# | Take the following code : The identifier foo has two types : IFoo - This is the type the compiler will enforce . I will only be able to call methods that are part of the IFoo contract , otherwise I 'll get a compiler error.FooImplementation - This is the type as known by the runtime . I can downcast foo to a FooImpleme... | IFoo foo = new FooImplementation ( ) ; | What is the proper terminology for each type of an identifier ? |
C# | I have a table that stores the history of changes on a product and want to get a list of records that have a change in Col1 or Col2 or Col3 but not show me records that do not have a change in any of these three columns .Here 's an example done in SQL . How do you do with Linq ? Create temporary table for testingInsert... | CREATE TABLE # ProductHistorical ( IdProductHistorical int IDENTITY ( 1,1 ) NOT NULL , IdProduct int NOT NULL , DateChange datetime NULL , Col1 int NOT NULL , Col2 int NOT NULL , Col3 int NOT NULL , CONSTRAINT PK_ProductHistorical PRIMARY KEY CLUSTERED ( IdProductHistorical ASC ) ) GO INSERT # ProductHistorical ( IdPro... | Linq Filter row differences in historical |
C# | We know that these two addition statements are equivalent and compile to the same IL code : However , when there is an explicit cast required I have noticed something strange : It is obvious why the second statement requires an explicit cast because the result of the addition is an integer . But the weird thing to me i... | int x = 100 ; x += 100 ; x = x + 100 ; byte b = 100 ; b += 200 ; // Compiles ( 1 ) b = b + 200 ; // Can not implicitly convert int to byte ( 2 ) b = ( byte ) ( b + 200 ) ; // Compiles ( 3 ) int x = 100 ; long y = 200 ; x += y ; | Why is x = x + 100 treated differently than x += 100 that compiles to the same IL ? |
C# | I have a bit of a hard time putting this just in words , so I 'll use some code to help explain myself and my problem.So imagine I have two classes ClassA and ClassB : as you can see ClassB contains ClassA , but I have another class for it ClassAOwned because I want ClassB to own ClassA ( flatten its columns into Class... | class ClassA { public int ClassAId { get ; set ; } public string Name { get ; set ; } } [ Owned ] class ClassAOwned { public int ClassAId { get ; set ; } public string Name { get ; set ; } } class ClassB { public int ClassBId { get ; set ; } public string Action { get ; set ; } public ClassAOwned ClassA { get ; set ; }... | How to set class property 's value to be set to generated id value of another class on insertion to database ? |
C# | Q1 Why do new classes from .NET implement interfaces only partially ? Q2 Shall I do the same in my code ? I asked this question here , so I thought , okay that was long time ago , you can have different usage etc etc , and now such implementation is supported only for consistency reasons . But new classes also do that.... | int [ ] list = new int [ ] { } ; IList iList = ( IList ) list ; ilist.Add ( 1 ) ; //exception here ICollection c = new ConcurrentQueue < int > ( ) ; var root = c.SyncRoot ; //exception here | Why do core types implement interfaces only partly ? |
C# | The given codeemits the following warning : If I remove .Select ( ) clause it disappears.But it 's not clear to me what exactly I need to .Ensure so that the cccheck was satisfied . | static public int Q ( ) { return Enumerable.Range ( 0 , 100 ) .Select ( i = > i ) .First ( ) ; } warning : CodeContracts : requires unproven : Any ( source ) | Contract that ensures the IEnumerable is not empty |
C# | I have a theorical/pratical question about how inheritance works in C # .Let 's say that I have to model some autos , so I have a few common methods that all the autos must implement and a pilot should know . In code-words this should be an Interface : Now , all kind of car should have some common technical implementat... | interface Automobile { void speedup ( ) ; void break ( ) ; void steer ( ) ; //bla bla } abstract class Car : Automobile { int fuelLevel ; // for example ... . public abstract void speedup ( ) ; public abstract void break ( ) ; public abstract void steer ( ) ; } class Ferrari : Car { public void speedup ( ) { ... } publ... | About C # and Inheritance |
C# | I could n't find any information on this through professor Google , so here I am . Take the given path name and paste it into Windows Explorer . I stumbled across this after discovering bug in my code that generated the paths with an extra ' . ' in the path name before a directory \ separator ... In code , .NET will ac... | @ '' C : \\pathto.\file.ext '' @ '' C : \\pathto\file.ext '' | Strange behavior from .NET regarding file paths |
C# | I am trying to read the System Event Logs in C # .NET 3.5 with the following method EventLog.GetEventLogs . This seems to be working perfectly for all kinds of Event Logs that I want to take a look at . There is but one exception : Microsoft-Windows-Kernel-Power Event Logs which can be read but produces the following M... | var myEventLogs = new List < myModels.EventLogEntry > ( ) ; foreach ( var eventLog in EventLog.GetEventLogs ( ) ) { foreach ( var entry in eventLog.Entries ) { if ( entry.Source.IndexOf ( `` kernel-power '' , StringComparison.OrdinalIgnoreCase ) == -1 & & entry.Message.IndexOf ( `` kernel-power '' , StringComparison.Or... | The description for Event ID ' X ' in Source 'Microsoft-Windows-Kernel-Power ' can not be found |
C# | I 'm facing a general question where I ca n't find a good example to try-it-for-myself . Google is n't a help neither.Imagine a structure like this : What if the server is slow and takes a while to accept the mail . Is it possible that the SmtpClient is disposed before the operation is done ? Will it be canceled or bro... | MailMessage mail = new MailMessage ( sender , receiver ) ; using ( SmtpClient client = new SmtpClient ( ) ) { client.Host ... client.Port ... mail.subject ... mail.body ... client.SendAsync ( mail ) ; } | Using-statement with async call | Cancel operation ? |
C# | I have an array of Vehicles in C # and some vehicles are Cars and others are SUVs . I am wondering what is the best way to fetch car with lowest weight . If no car is found in the array then find SUV with lowest weight.Below is code segment I have using LINQ . I am wondering if there is better way to fetch this using o... | Vehicle listVehicles [ ] = ... Vehicle lightestVehicle = ( from aVehicle in listVehicles where aVehicle.Type == CAR orderby aVehicle.Weight ascending ) ? .FirstOrDefault ( ) ; if ( null == lightestVehicle ) lightestVehicle = ( from aVehicle in listVehicles where aVehicle.Type == SUV orderby aVehicle.Weight ascending ) ... | Selecting first element of a group from LINQ search results |
C# | Most , if not all , examples of Dapper in .NET I 've seen use a structure like this : If you have a Web API , is it wise to make a new connection every time a request is made to the server ? Or would it be a better pattern to abstract the connection into another class and inject it into each controller so they are usin... | using ( SqlConnection conn = new SqlConnection ( ConnectionString ) ) { conn.Open ( ) ; return conn.Query < T > ( sql , param ) ; } | Reusing database connection with Dapper in .NET Web API |
C# | Suppose you have 2 classes like so : Now imagine you have an instance of each class and you want to copy the values from a into b . Is there something like MemberwiseClone that would copy the values where the property names match ( and of course is fault tolerant -- one has a get , and the other a set , etc . ) ? Somet... | public class ClassA { public int X { get ; set ; } public int Y { get ; set ; } public int Other { get ; set ; } } public class ClassB { public int X { get ; set ; } public int Y { get ; set ; } public int Nope { get ; set ; } } var a = new ClassA ( ) ; var b = new classB ( ) ; a.CopyTo ( b ) ; // ? ? | Is there anything built into .NET/C # for copying values between objects ? |
C# | I have an interface IKey which I want to have a method which will return the key as a string . We looked at having a method like this : which would return the string representation , but would have liked to be able to declare ToString ( ) again in the interface to force implementers to implement it , but it does n't fo... | String GetAsString ( ) ; public interface IKey { string ToString ( string dummyParameter=null ) ; } public class Key : IKey { public string ToString ( string abc = null ) { return `` 100 '' ; } } Key key = new Key ( ) ; Trace.WriteLine ( key.ToString ( ) ) ; Trace.WriteLine ( key.ToString ( null ) ) ; Trace.WriteLine (... | Is taking advantage of optional parameter edge cases to force implementations of ToString via an interface abuse of the language ? |
C# | i have this classand i have a manager that gets several lists of ConnectionResult and count each value greater then a specific number determined by configuration . my implementation is so : but i want to make it better , so i started to write it in linq and i got tobut this gives me an error of Can not implicitly conve... | public class ConnectionResult { private int connectionPercentage ; public int ConnectPercentage { get { return connectionPercentage ; } } public ConnectionResult ( int ip ) { // Check connection and set connectionPercentage } } public class CurrentConnections { private static CurrentConnections inst ; private CurrentCo... | Need better way to sum up data |
C# | For example , if I had two lists , I 'd do : Or if I had three , I 'd dobut if I do n't know at compile time how many lists are in the lists collection , how can I easily iterate over every permutation ? A C # solution is ideal , but a solution in any language that demonstrates a suitable algorithm would be handy.A goo... | foreach ( Item item1 in lists [ 0 ] ) foreach ( Item item2 in lists [ 1 ] ) // Do something with item1 and item2 foreach ( Item item1 in lists [ 0 ] ) foreach ( Item item2 in lists [ 1 ] ) foreach ( Item item3 in lists [ 2 ] ) // Do something with item1 , item2 , and item3 | How do you iterate over an arbitrary number of lists , including every permutation ? |
C# | Hello everyone : ) Here 's the situation : I have a baddy prefab which has two collider components : a simple CapsuleCollider2D used for physics , and a trigger PolygonCollider2D used only for mouse point collisions.The PolygonCollider2D is updated through an attached script ( Baddy.cs ) only when needed using : Yes , ... | if ( this.gameObject.GetComponent < PolygonCollider2D > ( ) ! =null ) { Destroy ( this.gameObject.GetComponent < PolygonCollider2D > ( ) ) ; } this.gameObject.AddComponent < PolygonCollider2D > ( ) ; this.gameObject.GetComponent < PolygonCollider2D > ( ) .isTrigger=true ; if ( MousePress ( ) ) { hit=Physics2D.Raycast (... | Prefab Collider2D not Recognized as Raycast Collider |
C# | Consider this code : In above code s is string but b is false.actually s as string , Why i get this result ? Why compiler has this behavior ? | class Program { static void Main ( string [ ] args ) { string s = null ; bool b = s is string ; Console.WriteLine ( b ) ; } } | Why null string is not a string object |
C# | I 'm wondering if there is a better way to approach this problem . The objective is to reuse code.Let ’ s say that I have a Linq-To-SQL datacontext and I 've written a `` repository style '' class that wraps up a lot of the methods I need and exposes IQueryables . ( so far , no problem ) .Now , I 'm building a service ... | public class ServiceLayer { MyClassDataContext context ; IMyRepository rpo ; public ServiceLayer ( MyClassDataContext ctx ) { context = ctx ; rpo = new MyRepository ( context ) ; } private IQueryable < MyClass > ReadAllMyClass ( ) { // pretend there is some complex business logic here // and maybe some filtering of the... | Is there anything wrong with having a few private methods exposing IQueryable < T > and all public methods exposing IEnumerable < T > ? |
C# | I have an Item class . I have around 10-20 derivatives of it each containing different types of data . Now when it comes to rendering different types of Item , I 'm forced to use likes of : Unfortunately @ Html.DisplayFor ( ) does not work in this case because the Model is type of Item , DisplayTemplates\Item.cshtml is... | < div > @ if ( Model is XItem ) { ... rendering logic 1 ... } @ if ( Model is YItem ) { ... rendering logic 2 ... } @ if ( Model is ZItem ) { ... rendering logic 3 ... } ... goes on and on forever ... < /div > | How to render derived types of a class differently ? |
C# | So I have an integer , e.g . 1234567890 , and a given set of numbers , e.g . { 4 , 7 , 18 , 32 , 57 , 68 } The question is whether 1234567890 can be made up from the numbers given ( you can use a number more than once , and you do n't have to use all of them ) . In the case above , one solution is:38580246 * 32 + 1 * 1... | static int toCreate = 1234567890 ; static int [ ] numbers = new int [ 6 ] { 4 , 7 , 18 , 32 , 57 , 68 } ; static int [ ] multiplier ; static bool createable = false ; static void Main ( string [ ] args ) { multiplier = new int [ numbers.Length ] ; for ( int i = 0 ; i < multiplier.Length ; i++ ) multiplier [ i ] = 0 ; i... | How can I determine if a certain number can be made up from a set of numbers ? |
C# | Say I have an array that is stored in 0° rotation : And I want it returned in a good approximation if I pass , for example 30° as parameter , it would be something like:45° would beI am aware of the solutions posted for 90° rotations . But I do n't think that will help me here ? I do n't have any examplecode because I ... | 0 0 1 0 00 0 1 0 0 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 01 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 10 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 class Rotation { public Rotation ( ) { A = new int [ xs , ys ] { { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 9,9,9,9,0,0,0 } , { 0,0,0,0,0,0,0 } , { 0,0,0,0,0... | How can I rotate a 2d array by LESS than 90° , to the best approximation ? |
C# | When I run this query in linqpad : It returns a record that matches.When I try running the same query in visual studio it does not return any matching records . This is the code I am using : Can anyone see why this it works in linqpad but does not work in visual studio ? | Customer.Where ( c = > ( c.CustomerName == `` test '' ) ) List < Customer > customerList = new List < Customer > ( ) ; using ( DBEntities db = new DBEntities ( ) ) { try { customerList = db.Customer.Where ( c = > ( c.customerName == `` test '' ) ) .ToList ( ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString (... | linq query for varchar field not returning any results |
C# | The following snippet is taken from an example of ComboBox : :DrawItem implementation on this MSDN page : I question this part : new SolidBrush ( animalColor ) Since this is neither deliberately given a Dispose nor is it wrapped in a using , I assume this is also an example of poor form , since the SolidBrush object wi... | e.Graphics.FillRectangle ( new SolidBrush ( animalColor ) , rectangle ) ; | Is an object creating using an `` inline '' new statement automatically disposed ? |
C# | Imagine that I have a visits index that contains documents of type 'visit ' that look like the following : The following function will return a histogram which returns buckets of visits for each day in the given range according to the given time zone.Now imagine that I changed things up a bit . Imagine that I added a n... | { `` id '' : `` c223a991-b4e7-4333-ba45-a576010b568b '' , // other properties `` buildingId '' : `` 48da1a81-fa73-4d4f-aa22-a5750162ed1e '' , `` arrivalDateTimeUtc '' : `` 2015-12-22T21:15:00Z '' } public Bucket < HistogramItem > Execute ( MyParameterType parameters ) { var buildingFilter = Filter < VisitProjection > .... | How can I reshape my data before I turn it into a histogram ? |
C# | I 'm working on a rehosted workflow designer using WF 4 , my application which uses this designer control is a multi-language application that loads 2 or more language specific resource dlls . if I have two satellite assemblies for one language such as `` en '' and `` en-US '' , designer throws an exception like this :... | Compiler error ( s ) encountered processing expression `` testExpression '' . The project already has a reference to assembly MyProject.resources . A second reference to ' C : \Dlls\en-US\MyProject.resources.dll ' can not be added . at Microsoft.VisualBasic.Activities.VisualBasicHelper.Compile [ T ] ( LocationReference... | WF 4 error with language specific resource dlls |
C# | I always see singletons implemented like this : Is there 's something wrong with implementing it like this : ? It gets lazy initialized on the very same moment as in the first implementation so I wonder why this is n't a popular solution ? It should be also faster because there 's no need for a condition , locking and ... | public class Singleton { static Singleton instance ; static object obj = new object ( ) ; public static Singleton Instance { get { lock ( obj ) { if ( instance == null ) { instance = new Singleton ( ) ; } return instance ; } } } protected Singleton ( ) { } } public class Singleton { static readonly Singleton instance =... | Singleton shortened implementation |
C# | I 'm creating an ASP.net website which handles thousands of requests and it all stems from one main object that they all share to read it . I 'm trying to wrap my head around these different types of locks.Some common questions i have for each.What is the scope of each lock Application , Session , ObjectWhen is it righ... | public class MyClass { lock { // DO COOL CODE STUFF . } } public class MyClass { Application.Lock // DO COOL CODE STUFF . Application.Unlock } public static object lockObject = new object ( ) ; public class MyClass { lock ( lockObject ) { // DO COOL CODE STUFF . } } private static readonly ReaderWriterLockSlim slimLock... | understanding Locking help ? |
C# | Question : Is this code look alright ? I understand that to be a key in the Map , Foo needs to override equals and hashcode methods - either override both or none.I was wondering what about List of objects as keys ? What does equality means when it comes to List ? is the map defined above safe from `` object-lost-in-th... | // No overrides required .. let CLR take care of equal and hashcode.Class Foo { public Name { get ; set ; } public Address { get ; set ; } } Dictionary < List < Foo > , int > map = new Dictionary < List < Foo > , int > ( ) ; | Can I use List of objects as Dictionary Keys ? |
C# | I want to take a List of strings with around 12 objects and split it into two List of strings but completely randomise it.Example of List : List 1 : Apply some logic here ... Result gives me two lists : List 1 : List 2 : I 'm a newbie to C # MVC , so I 've found some answers on Stack but none have been able to answer m... | EXAMPLE 1EXAMPLE 2EXAMPLE 3EXAMPLE 4EXAMPLE 5EXAMPLE 6EXAMPLE 7EXAMPLE 8 EXAMPLE 5EXAMPLE 6EXAMPLE 1EXAMPLE 8 EXAMPLE 2EXAMPLE 3EXAMPLE 4EXAMPLE 7 [ HttpPost ] public ActionResult Result ( Models.TeamGenerator model ) { var FormNames = model.Names ; string [ ] lines = FormNames.Split ( new [ ] { Environment.NewLine } ,... | Create two random lists from one list |
C# | Back in the old days of C , one could use array subscripting to address storage in very useful ways . For example , one could declare an array as such . This array represents an EEPROM image with 8 bit words.And later refer to that array as if it were really multi-dimensional storage I 'm sure I have the syntax wrong ,... | BYTE eepromImage [ 1024 ] = { ... } ; BYTE mpuImage [ 2 ] [ 512 ] = eepromImage ; | Question about array subscripting in C # |
C# | I have a binding : and this C # code : Note that GridLength is a structure : https : //docs.microsoft.com/en-us/dotnet/api/xamarin.forms.gridlength ? view=xamarin-formsDoes anyone know how I can bind to the value marked with ? ? ? For more explanation here 's what I am trying to do : I would like to be able to set the ... | public static readonly BindableProperty EntryWidthProperty = BindableProperty.Create ( nameof ( EntryWidth ) , typeof ( int ) , typeof ( SingleEntryGrid ) , 150 , BindingMode.TwoWay ) ; public int EntryWidth { get = > ( int ) GetValue ( EntryWidthProperty ) ; set = > SetValue ( EntryWidthProperty , value ) ; } var colu... | How can I bind to a Grid ColumnDefinition Width in C # |
C# | I assume the following sample gives a best practice that we should follow when we implement the IEnumerable interface.https : //docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenextHere is the question : Why should we provide two version of Current method ? When the version ONE ( object IEnumerato... | public class PeopleEnum : IEnumerator { public Person [ ] _people ; // Enumerators are positioned before the first element // until the first MoveNext ( ) call . int position = -1 ; public PeopleEnum ( Person [ ] list ) { _people = list ; } public bool MoveNext ( ) { position++ ; return ( position < _people.Length ) ; ... | C # - Why implement two version of Current when realizing IEnumerable Interface ? |
C# | Based on random Internet comments , I 've always believed that the C # compiler does simple optimizations to the IL ( removing always-true if-statements , simple inlining , etc ) , then later the JIT performs the real , complex optimizations.As just one example , on the documentation for the /optimize compiler flag , i... | bool y = true ; if ( y ) Console.WriteLine ( `` yo '' ) ; if ( true ) { Console.WriteLine ( `` yo '' ) ; } static void DoNothing ( ) { } static void Main ( string [ ] args ) { DoNothing ( ) ; Console.WriteLine ( `` Hello world ! `` ) ; } private static void DoNothing ( ) { } private static void Main ( string [ ] args )... | Does the C # language compiler perform any actual optimizations on its own ? |
C# | Word seems to use a different apostrophe character than Visual Studio and it is causing problems with using Regex . I am trying to edit some Word documents in C # using OpenXML . I am basically replacing [ [ COMPANY ] ] with a company name . This has worked pretty smoothly until I have reached my corner case of compani... | Regex apostropheReplace = new Regex ( `` s\\ 's '' ) ; docText = apostropheReplace.Replace ( docText , `` s\ ' '' ) ; Regex apostrophyReplace = new Regex ( `` s\\ ’ s '' ) ; docText = apostrophyReplace.Replace ( docText , `` s\ ' '' ) ; | Issue with find and replace apostrophe ( ' ) in a Word Docx using OpenXML and Regex |
C# | I 'm experimenting with locks that do n't require atomic instructions . Peterson 's algorithm seemed like the simplest place to start . However , with enough iterations , something goes wrong.Code : When I run this , I consistently get < 2,000,000 . What 's going on ? | public class Program { private static volatile int _i = 0 ; public static void Main ( string [ ] args ) { for ( int i = 0 ; i < 1000 ; i++ ) { RunTest ( ) ; } Console.Read ( ) ; } private static void RunTest ( ) { _i = 0 ; var lockType = new PetersonLock ( ) ; var t1 = new Thread ( ( ) = > Inc ( 0 , lockType ) ) ; var ... | Why does Peterson 's lock fail in this test ? |
C# | I mostly understand deferred execution , but I have a question about a particular case : Given a code fragment such ashow many times is the query resultsOfInterest executed ? Once when setting up the foreach loop , or once for every element ' x ' ? Would it be more efficient with ? TIA | var resultsOfInterest = from r in ... select r ; foreach ( var x in resultsOfInterest ) { //do something with x } foreach ( var x in resultsOfInterest.ToArray ( ) ) { //do something with x } | Linq deferred operations |
C# | I want to create a library that will create objects using a user-defined function and modify them using another user-defined function . I have an OCaml background and see a fairly straightforward way to implement it : The problem is that I want that library to be easy to call from C # : having functions as arguments is... | //user sidetype userType = { mutable time : float } let userInitialization ( ) = { time = 0 . } let userModification t = t.time < - t.time+1.//my sidelet algo initialization modification n = let a = Array.init n ( fun _ - > initialization ( ) ) modification a . [ 0 ] a | OO alternative to polymorphism in F # when calling F # from C # |
C# | I was wondering why ReSharper does warn me , when I 'm trying to convert a char to a string without giving a specific culture info.Is there any case , where it could be converted differently on two systems ? Example : The following ReSharper warning will pop up by default : Specify a culture in string conversion explic... | var str = ' '.ToString ( ) ; | Why does ReSharper warn at Char.ToString ( ) when not specifying CultureInfo explicitly ? |
C# | I can refactor this code ( popular as/null check pattern ) ..into a nice `` is '' type pattern expression : ..which is cool ... I think ... Is it ? But now I am also thinking to refactor..into : Note : there is no as and SomeMethod ( ) already returns MyType . It looks like ( pseudocode ) if ( A is A ) and may easily c... | var a = b as MyType ; if ( a ! = null ) { ... } if ( b is MyType a ) { ... } var a = SomeMethod ( ) ; if ( a ! = null ) { ... } if ( SomMethod ( ) is MyType a ) { ... } | The `` is '' type pattern expression for null check |
C# | I 'm curious if it is possible to determine whether or not an Assembly has referenced a particular class or not . I 'm currently using Reflection to load Assemblies and then I determine what Assemblies are being referenced from within the assembly I am loading : Now that I know what Assemblies are referenced , I want t... | foreach ( var vReferencedAssembly in vSomeAssembly.GetReferencedAssemblies ( ) ) File.Create ( vSomeFile ) ; | Determining if a class is referenced C # |
C# | I am developing a program which uses visual styles . The Main method looks like this : The program also works as a plugin of another application and it is started , in this case , via COM . The problem is that the calling application ( the COM client ) does n't call EnableVisualStyles and it is out of my control . In t... | [ STAThread ] static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new Form ( ) ) ; } public static void StartAsPlugin ( ) { Application.EnableVisualStyles ( ) ; Form form = new Form ( ) ; form.ShowDialog ( ) ; } < ? xml version= '' 1.0 ... | Visual styles do n't work on an in-process COM server |
C# | In Visual Studio 2013 Ultimate , Microsoft introduced a feature named CodeLens . A handy feature which ( among others ) has the ability to count the number of times a method is referenced in your project . At the moment we 're using VS2015 Pro and I 'm working in a big solution with multiple projects in it . The proble... | public class MapItem { public int Id { get ; set ; } public string Provider { get ; set ; } public string Value { get ; set ; } public bool MainItem { get ; set ; } public int ? MapId { get ; set ; } public override string ToString ( ) { return $ '' Provider : { Provider } , Value : { Value } , MainItem : { MainItem } ... | Prevent Visual Studio from counting references of certain methods |
C# | I have some code that I have no control of . This code accepts an object parameter and attempts to cast it to a type known at compile time like this : Is it possible in C # to design a custom class MyClass ( not derived from KnownType ) that can be passed as parameter to the above code and be converted to KnownType by ... | KnownType item = ( KnownType ) parameter ; protected KnownType ConvertToKnownType ( ) { // conversion code goes here } public static implicit operator KnownType ( MyClass source ) { KnownType result ; // conversion goes here return result ; } | C # dynamic conversion through cast operator |
C# | Consider the following scenario of services and components in a sample C # console application Let 's imagine to do the following registrations inside the composition root : This kind of scenario works fine and I did so several times.What if , for some reason , I would like to inject inside the constructor of Consumer ... | public interface IService { } public class FooService : IService { } public class BarService : IService { } public class BuzzService : IService { } public class AwesomeService : IService { } public class Consumer { public Consumer ( IEnumerable < IService > services ) { // do some initilization work here ... } } public... | Castle Windsor : inject IEnumerable < IService > using only a subset of registered components for IService |
C# | I was curious on the overhead of a large structure vs. a small structure in using operators + and * for math . So I made two struct , one Small with 1 double field ( 8 bytes ) and one Big with 10 doubles ( 80 bytes ) . In all my operations I only manipulate one field called x.First I defined in both structures mathemat... | public static Small operator + ( Small a , Small b ) { return new Small ( a.x + b.x ) ; } public static Small operator * ( double x , Small a ) { return new Small ( x * a.x ) ; } public double TestSmall ( ) { pt.Start ( ) ; // pt = performance timing object Small r = new Small ( rnd.NextDouble ( ) ) ; //rnd = Random nu... | Peculiar result relating to struct size and performance |
C# | I 'm trying to check if an enum option is contained in the available options.Its a little bit difficult for me to explain it in english.Here 's the code : I 'm trying to check if the me varliable is contained in the available variable.I know it can be done because it 's used with the RegexOptions too . | public enum Fruits { Apple , Orange , Grape , Ananas , Banana } var available = Fruits.Apple | Fruits.Orange | Fruits.Banana ; var me = Fruits.Orange ; | c # check enum is contained in options |
C# | I 'm in need to create a method which allows me to populate a List < string > with the values of the constants that are defined in the own class.To give you a quick example of the numerous ( 20 in total ) constants that are defined in the class : As you can see , the name of the constant equals the value of it , if tha... | private const string NAME1 = `` NAME1 '' ; private const string NAME2 = `` NAME2 '' ; private const string NAME3 = `` NAME3 '' ; ... public static List < string > GetConstantNames ( ) { List < string > names = new List < string > ( ) ; Type type = typeof ( ClassName ) ; foreach ( PropertyInfo property in type.GetType (... | Method to populate a List < string > with class constant values . C # |
C# | I am trying to dynamically get the schema of one of my views in SQLite using C # . I am using this code : Its working perfectly for all my tables and views except for one view . For some reason , the data type for the field called SaleAmount is coming up blank . There is nothing in the row [ `` DATA_TYPE '' ] element.H... | using ( var connection = new SQLiteConnection ( ConnectionString ) ) { connection.Open ( ) ; using ( DataTable columns = connection.GetSchema ( `` Columns '' ) ) { foreach ( DataRow row in columns.Rows ) { string dataType = ( ( string ) row [ `` DATA_TYPE '' ] ) .Trim ( ) ; // doing irrelevant other stuff here } } } SE... | ADO.Net reporting empty data type in SQLite |
C# | I was thinking about GUIDs recently , which led me to try this code : You can see that all of the bytes are there , but half of them are in the wrong order when I use BitConverter.ToString . Why is this ? | Guid guid = Guid.NewGuid ( ) ; Console.WriteLine ( guid.ToString ( ) ) ; //prints 6d1dc8c8-cd83-45b2-915f-c759134b93aaConsole.WriteLine ( BitConverter.ToString ( guid.ToByteArray ( ) ) ) ; //prints C8-C8-1D-6D-83-CD-B2-45-91-5F-C7-59-13-4B-93-AAbool same=guid.ToString ( ) ==BitConverter.ToString ( guid.ToByteArray ( ) ... | Why are these two strings not equal ? |
C# | In my quest to the primes , I 've already asked this question : Ca n't create huge arrays which lead me to create my own class of fake arrays based on a dictionary of arrays ... : private Dictionary < int , Array > arrays = new Dictionary < int , Array > ( ) ; I can know create fake arrays of a lot of bool ( like 10 00... | public class CustomArray { private Dictionary < int , Array > arrays = new Dictionary < int , Array > ( ) ; public CustomArray ( ulong lenght ) { int i = 0 ; while ( lenght > 0x7FFFFFC7 ) { lenght -= 0x7FFFFFC7 ; arrays [ i ] = new bool [ 0x7FFFFFC7 ] ; i++ ; } arrays [ i ] = new bool [ lenght ] ; } } | Create huge dictionary |
C# | I have the following input text : I would like to parse the values with the @ name=value syntax as name/value pairs . Parsing the previous string should result in the following named captures : I tried the following regex , which got me almost there : The primary issue is that it captures the opening quote in `` John \... | @ '' This is some text @ foo=bar @ name= '' '' John \ '' '' The Anonymous One\ '' '' Doe '' '' @ age=38 '' name : '' foo '' value : '' bar '' name : '' name '' value : '' John \ '' '' The Anonymous One\ '' '' Doe '' name : '' age '' value : '' 38 '' @ '' ( ? : ( ? < =\s ) |^ ) @ ( ? < name > \w+ [ A-Za-z0-9_- ] + ? ) \... | Parsing text between quotes with .NET regular expressions |
C# | I 'd like to do something like this : Note : I 'm running tasks on the thread pool , so there is no async context.I 'd like to be able to tell the difference between an exception thrown immediately , and I 'm still on the calling thread ( e.g . parameter is invalid causing the function to abort ) , and an exception thr... | public async Task < int > DoWork ( int parameter ) { try { await OperationThatMayCompleteSynchronously ( parameter ) ; } catch ( Exception ) e { if ( completedSynchronously ) doSyncThing ( ) ; else doAsyncThing ( ) ; } } | async await exception catching - which thread am I on ? |
C# | Is it sufficient to compare the ManagedThreadId at the time an object is created and at the time a method is called to verify that it is n't being used in a multithreading scenario ? My intuition is often wrong about threading , so I wanted to check to see if there are edge cases I should be keeping in mind . | public class SingleThreadSafe { private readonly int threadId ; public SingleThreadSafe ( ) { threadId = Thread.CurrentThread.ManagedThreadId ; } public void DoSomethingUsefulButNotThreadSafe ( ) { if ( threadId ! =Thread.CurrentThread.ManagedThreadId ) { throw new InvalidOperationException ( `` This object is being ac... | How do I detect multi-threaded use ? |
C# | I ca n't quite explain to myself in clear terms why a Task spawn by a Timer works just fine but a Timer spawn by a Task does NOT.All relevant code is included below so you can easily reproduce it.Form.cs : ProcessDelayList.cs : ProcessDelay.cs : | private void Form1_Load ( object sender , EventArgs e ) { ProcessDelayList list = new ProcessDelayList ( ) ; foreach ( ProcessDelay p in list ) { //this works p.Start ( ) ; //this does NOT work //Task.Factory.StartNew ( ( ) = > p.Start ( ) ) ; } } public class ProcessDelayList : List < ProcessDelay > { public ProcessDe... | Timer Spawn By Task And Task Spawn By Timer |
C# | I have the following line of code , with works in VS 2015 and .Net 4.0 , but I am getting an error in VS 2013.Why it works in a different way ? | StringBuilder s = new StringBuilder ( `` test '' ) { [ 0 ] = 'T ' } ; | StringBuilder initializer works one way in VS2015 but another in VS2013 |
C# | Given this Java code , this outputs 0 and 4 : And with this identical C # code , this outputs 4 and 4using System ; Though I figure out that the output should be 4 and 4 on Java , but the answer is actually 0 and 4 on Java . Then I tried it in C # , the answer is 4 and 4What gives ? Java rationale is , during construct... | class A { A ( ) { print ( ) ; } void print ( ) { System.out.println ( `` A '' ) ; } } class B extends A { int i = Math.round ( 3.5f ) ; public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } void print ( ) { System.out.println ( i ) ; } } class A { internal A ( ) { print ( ) ; } virtual interna... | Java constructor is not so intuitive . Or perhaps it 's not Java , it 's C # that is not intuitive |
C# | That 's the best way I could think to ask the question , the detail is below . It 's taken me an hour just to figure out how to ask the question ! Let 's say that I have 5 ( or more ) types of text files - they are generated by a scientific instrument and each has certain results . Let 's call these `` types '' A , B ,... | A B C D E A 1 1 1 1 0 B 1 1 1 0 0 C 1 1 1 1 0 D 1 0 1 1 1 E 0 0 0 1 1 internal class CompatibilityCheck { private List < string > FileTypes ; public CompatibilityCheck ( ) { //Strings are unique types for text files FileTypes = new List < string > { `` A '' , `` B '' , `` C '' , `` D '' , `` E '' } ; int [ , ] Compatib... | How do I make a new list of strings from another list based on certain criteria ? |
C# | I have an array of custom objects named AnalysisResult . The array can contain hundreds of thousands of objects ; and , occasionally I need only the Distinct ( ) elements of that array . So , I wrote a item comparer class called AnalysisResultDistinctItemComparer and do my call like this : My problem here is that this ... | public static AnalysisResult [ ] GetDistinct ( AnalysisResult [ ] results ) { return results.Distinct ( new AnalysisResultDistinctItemComparer ( ) ) .ToArray ( ) ; } public static AnalysisResult [ ] GetDistinct ( AnalysisResult [ ] results ) { var query = results.Distinct ( new AnalysisResultDistinctItemComparer ( ) ) ... | How to report progress on a long call to .Distinct ( ) in C # |
C# | Edit # 2 : config.FilePath is showing that it 's looking at a different file than what I 'm expecting : `` C : \Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config '' . I was expecting it to use the web.config in my project . Need to figure out why that 's happening.I have a method in my web API where I 'm t... | public AuthorizationSetting GetAuthorizationSettings ( ) { var config = WebConfigurationManager.OpenWebConfiguration ( null ) ; var section = config.GetSection ( `` system.web/authorization '' ) as AuthorizationSection ; foreach ( AuthorizationRule rule in section.Rules ) { if ( rule.Action.ToString ( ) .ToLower ( ) ==... | Reading AuthorizationSection from web.config provides incorrect values |
C# | I have written a piece of optimized code that contains special cases for null and empty strings . I am now trying to write a unit test for this code . In order to do that , I need two empty ( zero-length ) string objects that are different objects . Like this : It turns out that most .NET Framework APIs string are chec... | string s1 , s2 ; Assert.IsTrue ( s1.Length == 0 & & s2.Length == 0 ) ; Assert.IsTrue ( ! ReferenceEquals ( s1 , s2 ) ) ; | How to manufacture an empty string in .NET ? |
C# | I 'm not a C # guy I 'm more an Objective-C guy but lately I 've seen a lot of implementations of : Instead of : One of the examples of this is the MVVM Light Framework , there the developer implements the data service contract ( and implementation ) using the first approach , so my question is : Why this ? Is just a m... | public void Method ( Action < ReturnType > callback , params ... ) public ReturnType Method ( params ... ) | Action < T > vs Standard Return |
C# | I have a text file which has lines of data separated by newlines . What I 'm trying to do is count the number of lines in the file , excluding the ones that are only a newline . I 'm trying to use a regular expression to look at each line as it is read , and if it starts with a newline character not include it in my li... | public int LineCounter ( ) { StreamReader myRead = new StreamReader ( @ '' C : \TestFiles\test.txt '' ) ; int lineCount = 0 ; string line ; while ( ( line = myRead.ReadLine ( ) ) ! = null ) { string regexExpression = @ '' ^\r ? \n '' ; RegexOptions myOptions = RegexOptions.Multiline ; Match stringMatch = Regex.Match ( ... | Match only a newline character |
C# | Why C # compiler does not allow you to compile this : but does allow you to compile : where MyStruct is defined as : Update : in the firsts case the error is : Error 1 Use of unassigned local variable ' a ' | int a ; Console.WriteLine ( a ) ; MyStruct a ; Console.WriteLine ( a ) ; struct MyStruct { } | Differences between user created structs and framework structs in .NET |
C# | I am a reasonably experiences hobby programmer , and I have good familiarity with C++ , D , Java , C # and others.With the exception of Go , almost every language requires me to explicitly state that I am implementing an interface . This is borderline ridiculous , since we today have compilers for languages like Haskel... | interface ITest { void Test ( ) ; } class Test { void Test ( ) { } } void main ( ) { ITest x ; x = new Test ; } | What other languages support Go 's style of interfacing without explicit declaration ? |
C# | I 'm attempting to add an error to the ModelState by using nameof : In the view , this has been tagged with a name of Foo.Bar . When I add a model state error , I have to key that error to a name , so I use nameof ( Foo.Bar ) - however this just gives me Bar , when I need Foo.Bar . Right now I can hardcode Foo.Bar but ... | @ Html.ValidationMessageFor ( m = > m.Foo.Bar ) | using nameof ( ) to inspect class name with its parent for MVC validation |
C# | I have some code that takes a value ( of type object ) and tries to cast it to an IEnumerable of ints and uints like so : When the value is initialized this way : both idList and uintList have values , but calling idList.ToList ( ) results in an ArrayTypeMismatchException . However , when the value is generated with ne... | var idList = value as IEnumerable < int > ; var uintList = value as IEnumerable < uint > ; uint number = 1 ; object value = new [ ] { number } ; | Why does casting a value as IEnumerable < T > behave differently based on how I initialized the value ? |
C# | Let say I have The question is are there two iterations or just one.In other words , is that equivalent in performance to : | IEnumerable < int > list = new int [ ] { 1 , 2 , 3 } ; List < int > filtered = list.Select ( item = > item * 10 ) .Where ( item = > item < 20 ) .ToList ( ) ; IEnumerable < int > list = new int [ ] { 1 , 2 , 3 } ; List < int > filtered = new List < int > ( ) ; foreach ( int item in list ) { int newItem = item * 10 ; if ... | Does Select followed by Where result in two iterations over the IEnumerable ? |
C# | I want to make it so that if the value of subs is not `` '' then the ULs go before and after it and into the variable sL . If subs is `` '' then sL get the value `` '' But it does n't seem to work . Is my format correct ? | var sL = ( subs ! = `` '' ) ? `` < ul > '' + subs + `` < /ul > '' : `` '' ; | Confused about the ? operator in c # |
C# | I have a base abstract class and its abstract type parameter as : Then I have number of children classes inherent from it : Now , I want to put a Dictionary to keep track of the databases and a method to return them using DatabaseItem type , something like this : Then it gave me `` 'T ' must be a non-abstract type with... | public abstract class Database < T > where T : DatabaseItem , new ( ) { protected List < T > _items = new List < T > ( ) ; protected virtual void Read ( string [ ] cols ) { T item = new T ( ) ; ... } public abstract class DatabaseItem { ... } public class ShopDatabase : Database < ShopItem > { } public class ShopItem :... | Handling classes inherent from abstract class and type parameter |
C# | I have a list of numbers and I want to find closest four numbers to a search number.For example if the search number is 400000 and the list is : { 150000 , 250000 , 400000 , 550000 , 850000 , 300000 , 200000 ) , then the closest 4 numbers would be : Any help or suggestion would be appreciated . | { 300000 , 400000 , 250000 , 550000 } | C # linq list find closest numbers |
C# | I have an API call using SmartyAddress , here is the result returned from the API call : Now I would like to use JSON to return this result especially the analysis component , and here is the code I tried to write , but it always gives me the error : can not deserialize the current json object into type 'system.collect... | [ { `` input_index '' : 0 , `` candidate_index '' : 0 , `` delivery_line_1 '' : `` xx '' , `` last_line '' : `` xx '' , `` delivery_point_barcode '' : `` xx '' , `` components '' : { `` primary_number '' : `` xx '' , `` street_name '' : `` xx '' , `` street_suffix '' : `` xx '' , `` city_name '' : `` xx '' , `` state_a... | API Call in C # using JSON |
C# | If I have a routine that can throw an ArgumentException in two places , something like ... What ’ s the best way of determining in my calling procedure which of the two exceptions was thrown ? Or Am I doing this in the wrong fashion ? | if ( Var1 == null ) { throw new ArgumentException ( `` Var1 is null , this can not be ! `` ) ; } if ( Val2 == null ) { throw new ArgumentException ( `` Var2 is null , this can not be either ! `` ) ; } | Which of the two exceptions was called ? |
C# | I 'll give a quick example of what I 'm familiar with implementing using C. The focus I think is on how the data can be used , not so much what I 'm doing with it in the example : ) So I 'm looking for advice on how similar data tables , or reference data , are implemented in C # . I 'm getting the hang of the higher l... | typedef struct { const char *description ; uint32_t colour_id ; uint32_t quantity ; } my_data_t ; const my_data_t ref_data [ ] = { { `` Brown Bear '' , 0x88 , 10 } , { `` Blue Horse '' , 0x666 , 42 } , { `` Purple Cat '' , 123456 , 50 } , } ; void show_animals ( void ) { my_data_t *ptr ; ptr = & ref_data [ 2 ] ; consol... | Coming from a C background , what 's a good way to implement const reference data tables/structures in C # ? |
C# | From what I can piece together : int SalesTeamId is a variable and person is being assigned to the variable . After that I 'm lost . Any guidance ? | int salesTeamId = person == null ? -1 : person.SalesTeam.Id ; | Could someone interpret this line of code ? |
C# | The MessageBox.Show call below shows `` Inner '' . Is this a bug ? | private void Throw ( ) { Invoke ( new Action ( ( ) = > { throw new Exception ( `` Outer '' , new Exception ( `` Inner '' ) ) ; } ) ) ; } private void button1_Click ( object sender , EventArgs e ) { try { Throw ( ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; // Shows `` Inner '' } } | Control.Invoke unwraps the outer exception and propagates the inner exception instead |
C# | I 'm seeing some strange behavior when using a nullable long switch statement in VS2015 Update 1 that I 'm not seeing in other Visual Studio releases where it runs as expected.This sample code produces the following output ( Aligned for readability ) : I 'm only observing this behavior with Nullable types . Non-nullabl... | class Program { static void Main ( string [ ] args ) { NullableTest ( -1 ) ; NullableTest ( 0 ) ; NullableTest ( 1 ) ; NullableTest ( 2 ) ; NullableTest ( null ) ; } public static void NullableTest ( long ? input ) { string switch1 ; switch ( input ) { case 0 : switch1 = `` 0 '' ; break ; case 1 : switch1 = `` 1 '' ; b... | Nullable Long switch statement not producing expected output in VS2015 |
C# | What are the rules when resolving variable number of parameters passed by params ? Suppose , that I have the code : How is Method ( a , b , c ) resolved , if a is a IMyInterface ? Can I be sure , that C # will always try to select most matching overload ? | public void Method ( params object [ ] objects ) { } public void Method ( IMyInterface intf , params object [ ] objects ) { } | Resolving params in C # |
C# | In C # , the following method will not compile : The compiler errors : 'IsItTrue ( ) ' : not all code paths return a value , which makes perfect sense . But the following compile without any issue . Which looks wrong as no return statement at all . Why is it so ? Any help here ... , | public bool IsItTrue ( ) { } public bool IsItTrue ( ) { while ( true ) { } } | Why compiler behaves differently with this code ? |
C# | I 've built a method that returns me an instance of attribute if it is found on the property : In order to get instance , I have to invoke : And it works fine , I get exact instance of the attribute class.However , I do n't like that I have to use new NullableAttribute ( ) as parameter , I 'd like to have invoke look l... | public static U GetPropertyAttribute < T , TProperty , U > ( this T instance , Expression < Func < T , TProperty > > propertySelector , U attribute ) where U : Attribute { return Attribute.GetCustomAttribute ( instance.GetType ( ) .GetProperty ( ( propertySelector.Body as MemberExpression ) .Member.Name ) , typeof ( U ... | Inferring 2 out of 3 generic types |
C# | I was just wondering if a simple static function using the ? : operator is inlined during just in time compilation . Here is an arbitrary example using the code.Which gives the following IL : Or would the simplier alternative be inlined ? Here is the IL for it : The ? : operator apparently generates a more concise MSIL... | public static int Max ( int value , int max ) { return value > max ? max : value ; } Max : IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.1 IL_0003 : bgt.s IL_0008IL_0005 : ldarg.0 IL_0006 : br.s IL_0009IL_0008 : ldarg.1 IL_0009 : stloc.0 IL_000A : br.s IL_000CIL_000C : ldloc.0 IL_000D : ret public static int Max ( in... | Are Methods using the ? : Operator Inlined during JIT compilation ? |
C# | I need an accurate searching function whether in jquery or c # . If possible I want the searching as brilliant as google : - ) So here is c # code : Brief explanation : This searches all users in database that has complete information . It searches all users except the currently logged in user . And the result : The en... | string [ ] ck = keyword.Split ( new string [ ] { `` `` , `` , '' , `` . '' } , StringSplitOptions.RemoveEmptyEntries ) ; using ( dbasecore db = ConfigAndResourceComponent.BaseCampContext ( ) ) { var results = ( from u in db.users join uinfo in db.userinfoes on u.UserID equals uinfo.UserID where u.UserID ! = userid & & ... | How to create more accurate searching ? |
C# | I 'm looking to understand a bit more about LINQ and use it a little more , so a little bit of self development work going here ... I have an object as follows : Now , given a list of players , I 'd like to select the ones that have formerly played for various selected clubs , I could do it easily by a couple of foreac... | public class Player ( ) { public string Name { get ; set ; } public Club currentClub { get ; set ; } public IEnumerable < Club > previousClubs { get ; set ; } } var prevClubs = from player in players from clubOriginal in player.previousClubs from clubSecond in player.previousClubs from clubThird in player.previousClubs... | Object population with LINQ |
C# | I ca n't figure it out , where did I go wrong ? I got the following datetime string , and need to parse it to datetime : And I trying to parse it like this : When trying to do this it returns `` string was not recognized as a valid DateTime '' Any tip ? | string timestr = `` 1/20/2014 12:05:16 AM '' DateTime.ParseExact ( timestr , `` MM/dd/yyyy hh : mm : ss tt '' , null ) ; | How can I parse this datetime string ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.