lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have Edges and Vertexes are collected into listsSome example : So I would like to make IDictionary < Edge , bool > which would hold edges ( A -- > B and B -- > A would be like 1 ) , and bool - if it is two way or no.I need it because when I draw them now , it draws 2 arrows under one another . I would better make 1 a... | class Vertex { Graph _graph ; float x ; float y ; string key ; //and some similar atributes public IEnumerable < Edge > Edges { get { return _graph.Edges.Where ( s = > s.Source == this ) ; } } } class Edge { Graph _graph ; Vertex source ; Vertex target ; } class Graph { private VertexCollection _vertexCollection ; // e... | LINQ , creating unique collection of a collection |
C# | My class looks like this , I added new property IsModified which can be nullable . I can create a new entity of type A using only Name and Key property , but when I try to update key for any existing records for which IsModified is null in db , I get this error from Entity Framework : System.Data.Entity.Validation.DbEn... | public class A { public long ID { get ; set ; } public string Key { get ; set ; } public bool ? IsModified { get ; set ; } public string Name { get ; set ; } public A ( ) { this.IsModified = false ; } } CREATE TABLE [ dbo ] . [ A ] ( [ ID ] [ bigint ] IDENTITY ( 1,1 ) NOT NULL , [ Name ] [ nvarchar ] ( max ) NOT NULL ,... | Validation failed for one or more entities in Entity Framework for nullable boolean property |
C# | I am experimenting with Generic Constraints . When declaring a constraint on a class as so : I am able to access method declared by IFooDoc within the methods of the DocumentPrinter class . However , if I make DocumentPrinter implement an interface that declares the contraint , eg : and then declare DocumentPrinter as ... | public class DocumentPrinter < T > where T : IFooDoc public interface IDocumentPrinter < T > where T : IFooDoc { void Add ( T fooDoc ) ; void PrintFoos ( ) ; } public class DocumentPrinter < T > : IDocumentPrinter < T > | C # Interface Contraints |
C# | I have these two classes in my code and a List of Class2 . I want to group the list elements by date and ID using LINQ . My list is similar to this : Sorry if this is a stupid question , but I am a beginner in C # programming and LINQ and I am not sure if this is even possible.This is what I have tried based on example... | public class Class1 { public string ID ; public int y ; public int z ; } public class Class2 { public List < Class1 > a ; public int p , q ; public string s ; public DateTime date ; } List < Class2 > object1 = new List < Class2 > { new Class2 { p = 5 , q = 6 , date = DateTime.Now , a = new List < Class1 > { new Class1 ... | Need help in a grouping using LINQ in C # |
C# | I 'm working on a project that publish to a multiple websites using a multiple accounts . each account can publish to a specific website . as shown in the 'Dict ' below . The problem is I 'm trying to distribute the publishing jobs on accounts fairly and making a distance between accounts that has more than 1 job.when ... | using System ; using System.Collections.Generic ; using System.Linq ; public class Program { public struct Job { public string Site { get ; set ; } public string Account { get ; set ; } } private static readonly Dictionary < string , List < string > > Dict = new Dictionary < string , List < string > > ( ) ; private sta... | Distributing jobs fairly on accounts - distribution algorithm |
C# | A pure method is defined as `` does not make any visible state changes '' .My method is writing a log message if one argument is null or an exception is thrown . Is it still pure ? Is writing to a logger a visible change ? Here 's the code : | /// < summary > /// Formats with invariant culture - wo n't throw an exception . /// < /summary > /// < param name= '' format '' > A composite format string. < /param > /// < param name= '' args '' > An object array that contains zero or more objects to format. < /param > /// < returns > A copy of format in which the f... | Is a method that is writing to a logger pure ? |
C# | I 'm currently using the httplistener authenticationselector delegate to do windows auth and ip checking and it 's working brilliantly in that it denies and allows exactly the clients it should be . However , the problem is that when someone gets denied , they get a 403 http response which seems to be interpreted by mo... | AuthenticationSchemeSelector pIPChecker = pRequest = > { if ( ! pfunIPChecker ( pRequest.RemoteEndPoint.Address ) ) { LogHelper.writeToEventLog ( `` WARNING , BANNED IP : `` + pRequest.RemoteEndPoint.Address.MapToIPv4 ( ) .ToString ( ) + `` attempted to login '' , EventLogEntryType.Warning , LogHelper.EventLogID.Permis... | Giving an authentication denied message in httplisteners authenticationselectordelegate |
C# | I am wondering if there is any difference between these two methods . Second one look more natural , but that should n't be the only reason to use it . Maybe there are some performance issues or some diabolic mambojambo related to any of them ? | void FirstMethod < T > ( T a ) where T : IEnumerable < Animal > { ... } void SecondMethod < T > ( IEnumerable < T > a ) where T : Animal { ... } | Constraint vs Parameter - way to force collection as parameter |
C# | After searching the interwebs , I 've managed to create a C # class to get a FileTimeUTC Hex String.For PowerShell I 've tried using this same code : The problem is I get a few error messages : I do n't know how to get this C # code valid for PowerShell and would like a working solution . I do n't know why PowerShell c... | public class HexHelper { public static string GetUTCFileTimeAsHexString ( ) { string sHEX = `` '' ; long ftLong = DateTime.Now.ToFileTimeUtc ( ) ; int ftHigh = ( int ) ( ftLong > > 32 ) ; int ftLow = ( int ) ftLong ; sHEX = ftHigh.ToString ( `` X '' ) + `` : '' + ftLow.ToString ( `` X '' ) ; return sHEX ; } } $ HH = @ ... | PowerShell - Convert FileTime to HexString |
C# | Consider the following code snippetwhy the delegate call and normal method invocation call different methods . | namespace ConsoleApplication1 { public delegate TResult Function < in T , out TResult > ( T args ) ; class Program { static void Main ( string [ ] args ) { Program pg =new Program ( ) ; Function < Object , DerivedClass > fn1 = null ; Function < String , BaseClass > fn2 = null ; fn1 = new Function < object , DerivedClas... | delegate covariance and Contavariance |
C# | I have a method that is taking in an Action < string > ( see simple example below ) , but in the calling method where the Action is constructed , Resharper is suggesting that a Local Function should be used.What are the recommended practices around using Local Functions in place of Actions , does it matter , or are the... | public void Caller ( ) { string holder ; Action < string > act = s = > holder = s ; void SetHolder ( string s ) = > holder = s ; DoStuff ( act ) ; DoStuff ( SetHolder ) ; } public void DoStuff ( Action < string > setHolder ) { setHolder ( `` holders new string '' ) ; } | Using a Local Function over an Action as an input param |
C# | I serialized a javascript array using JSON.stringify and got a string which I used it as : How do I convert 'test ' to a C # List variable ? | string test = `` [ [ 0,0 ] , [ 0,0 ] , [ 0,0 ] , [ 0,0 ] , [ 0,0 ] , [ 0,0 ] ] '' ; | How to split a string of array of arrays of integers into List < int [ ] > ? |
C# | I have classes A , B , C like this : My question is if B already has reference to C and A has reference to B why do A need to have reference to C ? This is not make sense no ? | //Class A is in Console application that has reference to class library that has class Bpublic class A { public void UseBObject ( ) { B BInstance=new B ( ) ; // error C is defined in assembly that is not referenced you must add reference that contains C ... } } //Class library that reference another library the contain... | c # references a uses b that inherits from c |
C# | So I just saw this line of code : Is there a reason it cant just be : | Item = ( int ? ) ( int ) row [ `` Item '' ] ; Item = ( int ? ) row [ `` Item '' ] ; | Is there a reason to cast to a type then to its nullable type ? |
C# | I have Specification pattern implementation and I wanted to change it to support contravariance . However interesting problem arose.this work as you can expectbut if I reverse the order of argument it does n't compile anymoreI understand why this happens but my question is - is there a way to have both working ? EDIT :... | public interface ISpecification < in T > { Func < T , bool > Predicate { get ; } bool IsSatisfiedBy ( T entity ) ; } public class Specification < T > : ISpecification < T > { public Specification ( Func < T , bool > predicate ) { this.Predicate = predicate ; } public Func < T , bool > Predicate { get ; private set ; } ... | Contravariance and operator overload |
C# | I am not sure if this is the right way or not . Is there a better way to do this : | public List < Category > ManyCategories ( IEnumerable < int > cats ) { string categoriesJoined = string.Join ( `` , '' , cats ) ; using ( var conn = new SqlConnection ( ) ) { conn.Open ( ) ; //make this a union all return _categories = conn.Query < Category > ( `` select Id , ParentId , Name from [ Meshplex ] . [ dbo ]... | How to use IN with Dapper |
C# | I am trying to translate C # code to nodejs and I 've hit a wall . One of the functions in C # uses a bytes to generate 3 numbers using BitConverter.toInt64 like so : As an example , if I use the array : Then the values for start , middle , and end are : But using NodeJS with the biguinut-format package I get the follo... | var hashText = //Generates Hash from an input here using ComputeHash var hashCodeStart = BitConverter.ToInt64 ( hashText , 0 ) ; var hashCodeMedium = BitConverter.ToInt64 ( hashText , 8 ) ; var hashCodeEnd = BitConverter.ToInt64 ( hashText , 24 ) ; //Does other stuff with the three pieces here var hash = new Byte [ ] {... | Simulating C # overflow in NodeJS |
C# | Invoking an extension method that works on a interface from an implementor seems to require the use of the this keyword . This seems odd . Does anyone know why ? Is there an easier way to get shared implementation for an interface ? This irks me as I 'm suffering multiple inheritance/mixin withdrawl.Toy example : | public interface ITest { List < string > TestList { get ; } } public static class TestExtensions { private const string Old = `` Old '' ; private const string New = `` New '' ; public static void ManipulateTestList ( this ITest test ) { for ( int i = 0 ; i < test.TestList.Count ; i++ ) { test.TestList [ i ] = test.Test... | Invoking interface extension methods from implementor is weird in C # |
C# | Currently I 'm reading a collection of items from a stream . I do this as following : Let say I have a stream which contains two items , and I do the following : Now result1 is 2 , while result2 is one.Now I noticed , that my null check is useless ? It seems that everytime I call that function it gets yielded anyway . ... | public class Parser { private TextReader _reader ; //Get set in Constructor private IEnumerable < Item > _items ; public IEnumerable < Item > Items { get { //I > > thought < < this would prevent LoadItems ( ) from being called twice . return _items ? ? ( _items = LoadItems ( ) ) ; } } public IEnumerable < Item > LoadIt... | yield always gets called |
C# | Edit : I noticed that the error does not only occur for the five XML reserved characters , but also for other special characters.i have a problem with the SAML request i am using to obtain a STS token . The SAML request is witten in XML.If the password sent with the request contains a character that is reserved by XML ... | lConnection.Client.Accept : = '*/* ' ; lConnection.Client.AcceptLanguage : = 'en-US ' ; lConnection.Client.UserAgent : = 'Mozilla/4.0 ( compatible ; MSIE 7.0 ; Windows NT 6.1 ; WOW64 ; Trident/5.0 ; SLCC2 ; .NET CLR 2.0.50727 ; .NET CLR 3.5.30729 ; .NET CLR 3.0.30729 ; Media Center PC 6.0 ; .NET4.0C ; .NET4.0E ; InfoPa... | Requesting STS Token via SAML with passwords containing special characters |
C# | I 'm attempting to create a common interface which will allow me n methods of interacting with a database . I want my business application to be able to instantiate any of the connection methodologies and be assured the interface is identical . Here 's a simplified version of what I 'm trying now.Database Interface whe... | public interface IDatabase { void setItem ( IElement task ) ; //this works fine List < T > listTasks < T > ( ) where T : IElement ; // this does n't } public interface IElement { int id { get ; set ; } } public class TaskElement : IElement { public int id { get ; set ; } public string name { get ; set ; } } public clas... | Implementing generic methods from an interface using another interface |
C# | I have an object . Usually it is either long or string , so to simplify the code let 's assume just that.I have to create a method that tries to convert this object to a provided enum . So : With strings it works well . With numbers it causes problems , because a default underlying type for enum is int , not long and I... | public object ToEnum ( Type enumType , object value ) { if ( enumType.IsEnum ) { if ( Enum.IsDefined ( enumType , value ) ) { var val = Enum.Parse ( enumType , ( string ) value ) ; return val ; } } return null ; } | How to convert an arbitrary object to enum ? |
C# | I have a list of formulae for combining elements : I want to ensure that given any random 4 elements , there will never be more than 1 applicable formula . For example the formulae below should not be allowed as if I get elements A , B , C and D then both are applicable : Every formula will consist of 3 elements on the... | A + B + C = XD + E + F = YG + H + I = Z A + B + C = XB + C + D = Y | Ensuring only a single formula could ever apply to 4 random elements |
C# | In the following code , I pass a struct into a constructor that is expecting a class . Why does this compile and run without error ( and produce the desired output ) ? If I change my Main ( ) method so that it includes a call to ClearEntity ( ) , as shown below , it still generates no error . Why ? | class Program { static void Main ( ) { var entity = new Foo { Id = 3 } ; var t = new Test < IEntity > ( entity ) ; // why does n't this fail ? Console.WriteLine ( t.Entity.Id.ToString ( ) ) ; Console.ReadKey ( ) ; } } public class Test < TEntity > where TEntity : class { public TEntity Entity { get ; set ; } public Tes... | Is `` where T : class '' not enforced in any way at compile time or run time ? |
C# | I am quite new in C # and I found something unexpected in string comparison which I do n't really understand . Can someone please explain me why the comparison between characters gave the opposite result as the comparison of one character length strings in the following code ? I expected that `` 9 '' < `` = '' will be ... | bool resChComp = ' 9 ' < '= ' ; bool resStrComp = String.Compare ( `` 9 '' , `` = '' ) < 0 ; Console.WriteLine ( $ '' \n ' 9 ' < '= ' : { resChComp } , \ '' 9\ '' < \ '' =\ '' : { resStrComp } '' ) ; ' 9 ' < '= ' : True , `` 9 '' < `` = '' : False | 1-length string comparison gives different result than character comparison ... why ? |
C# | This may well be well-known and discussed , but to my surprise I discovered today that you can give your own implementation of operators between nullables and their base types.This means that you can have a struct which can be checked for null , and return true.Now this would be convenient in my situation - on the advi... | public struct StringWrapper { private readonly string str ; public override string ToString ( ) { return str ; } public static bool operator == ( StringWrapper a , StringWrapper b ) { return a.str == b.str ; } public static bool operator ! = ( StringWrapper a , StringWrapper b ) { return ! ( a == b ) ; } public static ... | Implementing operators between nullables and base types - should I ? |
C# | I have these two lines , that do exactly the same thing . But are written differently . Which is the better practice , and why ? | firstRecordDate = ( DateTime ) ( from g in context.Datas select g.Time ) .Min ( ) ; firstRecordDate = ( DateTime ) context.Datas.Min ( x = > x.Time ) ; | Which is the better method to use LINQ ? |
C# | I have a data access class that took me a while to get working . For my app , I need to get different types of SQL Server tables where the WHERE clause only differs by the column name : some columns are read_time , others are ReadTime , and others are LastModifiedTime . So I thought I 'd pass in the WHERE clause so I d... | internal List < T > GetObjectsGreaterThanReadTime < T > ( Expression < Func < T , bool > > whereClause ) where T : class { Table < T > table = this.Database.GetTable < T > ( ) ; IEnumerable < T > objects = table.Where ( whereClause ) ; return objects.ToList ( ) ; } internal List < T > GetObjectsGreaterThanReadTime < T ... | Why are Func < > and Expression < Func < > > Interchangeable ? Why does one work in my case ? |
C# | For several days I just can not find the problem itself , which is really driving me crazy . I have asp.net ( mvc4 ) web application , where there are several index pages ( showing list ) , when clicking on any item in the list , it returns edit view page . In the edit page ( in the view itself ) - there is a submit bu... | [ HttpPost ] public ActionResult Edit ( [ ModelBinder ( typeof ( OpportunityBinder ) ) ] OpportunityModel draft ) { try { if ( Request.Params [ `` cancel '' ] ! = null ) { return RedirectToAction ( `` index '' , Utils.CrmDB.GetOpportunities ( ) ) ; } if ( draft.IsValid ( ) ) { if ( Utils.CrmDB.UpdateOpportunity ( draft... | Controller generate few threads , although not asked |
C# | i have a method that looks like this : and i have another method that looks like this : Is there any way to consolidate this as the only thing different is the property names ? | private double GetX ( ) { if ( Servings.Count > 0 ) { return Servings [ 0 ] .X ; } if ( ! string.IsNullOrEmpty ( Description ) ) { FoodDescriptionParser parser = new FoodDescriptionParser ( ) ; return parser.Parse ( Description ) .X ; } return 0 ; } private double GetY ( ) { if ( Servings.Count > 0 ) { return Servings ... | is there a way to remove duplication in this code |
C# | I have noticed a certain behavior when using unsafe modifier at the class-level on partial classes that I was hoping to get some clarification on.I have been working on a rather large-wrapper , that for the sake of sanity , am splitting across multiple files using the partial modifier . The wrapper makes heavy use of u... | public static unsafe partial class Ruby { [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static VALUE CLASS_OF ( VALUE obj ) = > ( ( RBasic* ) obj ) - > klass ; } public static unsafe partial class Ruby { [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static void* DATA_PTR ( VALUE obj ) ... | Why class-level `` unsafe '' modifier not consistent when using `` partial '' ? |
C# | I have 2 lists , one a list of file names , the second a list of file name stubs , i would like to select everything from the first list where the file name is like the file name stub.The query would return all records from the first list.Thanks in advance . | List < string > files = new List < string > ( ) { `` a.txt '' , `` b.txt '' , `` c.txt '' } ; List < string > fileStub = new List < string > ( ) { `` a '' , `` b '' , `` c '' } ; | Compare 2 List < string > with a LIKE clause |
C# | I 've neglected unit testing for some time . I wrote unit tests , but they were fairly poor.I 'm now reading through `` The art of unit Testing '' to bring myself up to scratch.If I have an interface such as : A concrete implementation of this interface contains : Adding an error or issue creates a new message with an ... | public interface INotificationService { void AddError ( string _error ) ; void AddIssue ( string _issue ) ; IEnumerable < string > FetchErrors ( ) ; IEnumerable < string > FetchIssues ( ) ; } private readonly ICollection < Message > messages ; [ Test ] public void FetchErrors_LoggingEnabledAddErrorFetchErrors_ReturnsEr... | Unit testing using two functions |
C# | I 'm working through the book Head First C # and consistently have issues when adding resources to a window . This is a 100 % repeatable error on any new WPF application I create when adding a new resource . The only way around this is to comment out the resource , build , and uncomment , as detailed in MVCE below . Im... | //MyDataClass.csusing System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace XAMLBuildErrorExample { class MyDataClass { public string Foo { get ; set ; } } } < Window x : Class= '' XAMLBuildErrorExample.MainWindow '' xmlns= '' http : //schemas.micro... | Adding a resource to WPF application causes build error |
C# | Let 's say I have a `` Processor '' interface exposing an event - OnProcess . Usually the implementors do the processing . Thus I can safely subscribe on this event and be sure it will be fired . But one processor does n't do processing - thus I want to prevent subscribers to subscibe on it . Can I do that ? In other w... | var emptyProcessor = new EmptyProcessor ( ) ; emptyProcessor.OnProcess += event_handler ; // This line should throw an exception . | .NET events - blocking subscribers from subscribing on an event |
C# | What is the difference between the two cases below : versusI have the same question in asp.net : versus | class Data { PersonDataContext persons = new PersonDataContext ( ) ; public Data ( ) { } } class Data { PersonDataContext persons ; public Data ( ) { persons = new PersonDataContext ( ) ; } } public partial class Data : System.Web.UI.Page { PersonDataContext persons = new PersonDataContext ( ) ; protected void Page_Loa... | What is the difference in how these objects are instantiated ? |
C# | My teacher asked us to make a program in the most efficient way possible and to use a switch case for this.The program asks the user for input , and depending on what the user inputs , the program will have to follow a set of instructions.If the input is `` A '' or `` a '' , the array has to be sorted from A to Z.If th... | switch ( choice.ToLower ( ) ) { case `` a '' : Array.Sort ( array ) ; break ; case `` z '' : Array.Sort ( array ) ; Array.Reverse ( array ) ; break ; case `` r '' : Array.Reverse ( array ) ; break ; } if ( choice.ToLower ( ) == `` a '' || choice.ToLower ( ) == `` z '' ) { Array.Sort ( array ) ; } if ( choice.ToLower ( ... | What is the most efficient way to execute this code ? |
C# | I 've met a piece of code that will cause a stack overflow exception only when a for loop repeats over a certain number of times.Here 's the code : When the method Test ( ) is executed , you can see a long series of `` 1 '' and `` 2 '' being printed on screen before the error actually happens . ( which I think means th... | public class Stackoverflow { public static void Test ( ) { List < int > list = new List < int > ( ) { 1 , 2 } ; Container container = new Container { List = list } ; for ( int i = 0 ; i < 10000 ; i++ ) // This matters { foreach ( var item in container.List ) { Console.WriteLine ( item ) ; } } } } public class Container... | How could a for loop be related to a stack overflow ? |
C# | I want to cut a string in c # after reading first and last alphabet.string name = `` 20150910000549659ABCD000007348summary.pdf '' ; After reading 1234 `` A '' comes and at last `` s '' comes so I want `` ABCD000007348 '' | string result = `` ABCD000007348 '' ; // Something like thisstring name = `` 1234 ABCD000007348 summary.pdf '' ; | Parse a string in c # after reading first and last alphabet |
C# | I 've been staring at this code which I found in another question ( copied verbatim below ) and I know it 's not much , but it 's escaping me how the i++ % parts works . | void Main ( ) { int [ ] a = new [ ] { 10 , 3 , 5 , 22 , 223 } ; a.Split ( 3 ) .Dump ( ) ; } static class LinqExtensions { public static IEnumerable < IEnumerable < T > > Split < T > ( this IEnumerable < T > list , int parts ) { int i = 0 ; var splits = from item in list group item by i++ % parts into part select part.A... | How does this linq code that splits a sequence work ? |
C# | I 'm changing a class from public abstract AwesomeClass , to public sealed AwesomeClass . I 've also added a new property . All existing members are unchanged . I know that this is a breaking change . Clients that have implemented AwesomeClass or relied on it being abstract via reflection will be broken.My question is ... | public abstract class AwesomeClass { public abstract Guid SuperGuid { get ; set ; } public abstract int SuperInt { get ; set ; } } public sealed class AwesomeClass { public Guid SuperGuid { get ; set ; } public int SuperInt { get ; set ; } public int OtherSuperInt { get ; set ; } } | Will change from abstract class to sealed class break simple client use |
C# | I have a sentence , `` Name # 2 '' , I need to replace ' # ' , with `` No . `` , Final sentence needs to be `` Name No . 2 '' .Code - Apparently the Regex.Replace fails to replace ' # ' with 'No ' , is there a correct way to approach the problem , via a regular expression.thanksThe reason I am looking for a regex patte... | string sentence = Regex.Replace ( `` Name # 2 '' , `` \\ # \\b '' , `` No . `` ) ; string pattern = string.Format ( @ '' \b { 0 } \b '' , context ) ; sentence = System.Text.RegularExpressions.Regex.Replace ( sentence , pattern , suggestion ) ; | Regex Pattern for string replace |
C# | I have a list of class A , class A contains a list of class B. I want to operate on all instances of B within all instances of class A . How can I iterate over all B i.e . foreach ( var b in myListOfA.ListOfB ) { } ? | var myListOfA = new List < A > ( ) ; class A { public List < B > ListOfB ; } | Linq - operating on lists of lists |
C# | I 've got some inherited code that has a tendency to pass objects around as interfaces ( IFoo , for example ) then , at arbitrary places in the code , spontaneously cast them to concrete implementations of those interfaces ( say , MyConcreteFoo ) .Here 's a silly example : What I 'd like to do is write an NDepend CQL q... | public bool IsThisFooScaredOfMonkeys ( IFoo foo ) { if ( foo is MyConcreteFoo ) { return ( ( MyConcreteFoo ) foo ) .BelievesMonkeysAreEvil ; } return false ; } | Can I use NDepend to count casts ? |
C# | I have following codeErorr : A local variable named ' b ' can not be declared in this scope because it would give a different meaning to ' b ' , which is already used in a 'child ' scope to denote something elseOk , editingError : The name ' b ' does not exist in the current context | using ( some code ) { var b = ... . } var b = ... using ( some code ) { var b = ... . } b = ... | Why c # compiler generates a compile error ? |
C# | I am very new to C # , so my question may be silly but I realy ca n't solve it by myself & googling . I need to check if year is leap , so : works fine . But I need to get Year from somewhere , e.g . MS SQL : ... Error : CS1040 : Preprocessor directives must appear as the first non-whitespace character on a lineBut why... | < mso : if runat=server condition= ' < % # DateTime.IsLeapYear ( 2000 ) % > ' > YEAR ( getDate ( ) ) AS yarr < mso : if runat=server condition= ' < % # DateTime.IsLeapYear ( < % # Convert.ToInt32 ( DataBinder.Eval ( Container.DataItem , `` yarr '' ) ) % > ) % > ' > | Checking if year is leap with c # |
C# | There 's plenty of code and example floating around on how you could use lambda expressions to raise INotifyPropertyChanged events for refactoring freiendly code . This is then typically used as : My question is , how would you achieve something similar on the receiving end of things , where you 'd typcially have a swi... | NotifyOfPropertyChanged ( ( ) = > PropertyName ) ; private void SomeObject_PropertyChanged ( object sender , PropertyChangedEventArgs args ) { switch ( args.PropertyName ) { case `` XYZ '' : break ; // ... } } public class MyClass { public static class Notifications { public const string Property1 = `` Property1 '' // ... | INotifyPropertyChanged with lambda based checkin on the receiving end |
C# | I have the following code : Response 1 and response 2 are totally independent and i want to parallelize the await task here . Basically response 2 takes a lot of time and hence is only invoked when response1 is success.Is there any way in which i can invoke both tasks and see the result of response 1 and if it is fail ... | //Await # 1var response1 = await doSomething ( ) ; if ( response1.isSuccess ) { //Await # 2var response2 = await doSomethingElse ( ) ; } | Skip the await task response conditional |
C# | I 'm implementing an interface in order to inject custom business logic into a framework that utilizes Microsoft Unity . My core issue is that a the interface I need to implement defines the following method : T has no constraints . In my code , I need to call a method from a different 3rd party library , with a method... | T InterfaceMethod < T > ( ) ; T AnotherMethod < T > ( ) where T : class ; | Implementing interface with generic type that is less constrained than that of a method I need to call |
C# | I have a test suite in Microsoft test manager . Each test is mapped to certain WorkItem ID . I want to run all tests having same workitem id together as a playlist . Below is exmaple of sample test.I tried but was not able to make a playlist by Workitem id . Please suggest if it is possible to do so . | [ TestMethod ] [ TestCategory ( `` Cat A '' ) ] [ Priority ( 1 ) ] [ WorkItem ( 5555 ) ] public void SampleTest ( ) { Do some thing } | Create a playlist of test methods having same workitem id in Microsoft test explorer |
C# | I know I can use a collection initializer to initialize a list : If I recall , this internally calls Add for each item.Why is there not a constructor for List < T > that takes a params T [ ] items ? | var list = new List < string > { `` test string 1 '' , `` test string 2 '' } ; var list = new List < string > ( `` test string 1 '' , `` test string 2 '' ) ; | Why is there not a constructor for List < T > that takes a params argument ? |
C# | I am in need of some assistance , I have a method which is repeated 6 times in my class , and the only thing that changes in each of the methods is the LINQ property ( in the example `` first name '' , but I also have one for last name , firm name , user id , status ) . I would like some help refactoring this so that I... | private static IQueryable < MyModel > FilterFirstName ( IQueryable < MyModel > query , string searchText , string searchFilter ) { switch ( searchFilter.ToLower ( ) ) { case `` contains '' : query = query.Where ( x = > x.FirstName.ToLower ( ) .Contains ( searchText.ToLower ( ) ) ) ; break ; case `` does not contain '' ... | Assistance with refactoring a LINQ method |
C# | Say I have 10 threads busily doing something and they sometimes call a methodHowever , I do n't want my 10 threads to wait on HeavyLifting ( w ) , but instead , dispatch the HeavyLifting ( w ) work to an 11th thread , the HeavyLifter thread and continue asynchronously . The HeavyLifter thread dispatched to should alway... | public HandleWidgets ( Widget w ) { HeavyLifting ( w ) } | dispatch work from many threads to one synchronous thread |
C# | How can I take n elements from a m elements collection so that if I run out of elements it starts from the beginning ? How can I get the expected list ? I 'm looking for a CircularTake ( ) function or something in that direction . | List < int > list = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; List < int > newList = list.Skip ( 9 ) .Take ( 2 ) .ToList ( ) ; List < int > expected = new List ( ) { 10,1 } ; CollectionAssert.AreEqual ( expected , newList ) ; | Take n elements . If at end start from begining |
C# | PredicamentI have a large dataset that I need to perform a complex calculation upon a part of . For my calculation , I need to take a chunk of ordered data from a large set based on input parameters.My method signature looks like this : Potential SolutionsThe two following methods spring to mind : Method 1 - WHERE Clau... | double Process ( Entity e , DateTimeOffset ? start , DateTimeOffset ? end ) double result = 0d ; IEnumerable < Quote > items = from item in e.Items where ( ! start.HasValue || item.Date > = start.Value ) & & ( ! end.HasValue || item.Date < = end.Value ) orderby item.Date ascending select item ; ... return result ; doub... | What is the most efficient way to obtain an ordered range using EntityFramework ? |
C# | Say I have some code such as the following : I then want to determine if result was the default value . However , I want to do so in a maintainable way so that if the element type of someCollection changes , the rest of the code does n't require changing.The way this typically seems to be done ( in a general sense ) is... | var someCollection = new int [ ] { } ; var result = someCollection.SingleOrDefault ( ) ; | What 's a maintainable way to determine if a value is set to its type 's default value ? |
C# | if I have a function like that 's used in alot of places , is there any possible harm in changing it to : Could this possibly break any code ? I ca n't think of anything ... but it may be possible ? | public void usefulUtility ( parameters ... ) { string c = `` select * from myDB '' ; do_a_database_call ( c ) ; } public bool usefulUtility ( parameters ... ) { string c = `` select * from myDB '' ; bool result = do_a_database_call ( c ) ; return result ; } | Any harm in changing a void return type to something else in a commonly used utility function ? |
C# | I have dictionary entries that are read to a Dictionary < string , string > myDict=null ; The entries are like : How would I retrieve lastLogin with lowercase key myDict [ `` lastlogin '' ] ? | `` user '' , '' Anthony '' '' lastLogin '' , '' May 10 2010 20:43 '' | How to override case sensitivity in IDictionary < string , string > |
C# | ProblemI 'm currently working on creating an application . In this application I was working with serializing a Func . This somehow crashed my application without an exception.Crashing without an exception made me curious on wtf is going on so I did some deep diving and after some digging finally found out that somewhe... | Expression < Func < string , int > > expr = ( t ) = > t.Length ; Func < string , int > exprCompiled = expr.Compile ( ) ; var aa = exprCompiled.Method.Module ; var bb = exprCompiled.Method.Module.Assembly ; //This code results in either an infinite loop or a Stackoverflow Exceptionvar tempresult = aa.Equals ( bb ) ; Con... | Why does comparing 2 .NET framework classes with eachother result in a stackoverflow exception ? |
C# | I am new to DDD and NHibernate , when I try to config for table ( using code-first ) with NHibernate fluent.In EntityFramework we can use ComplexTypeConfiguration to config for value object and using that config in many table , but I have no idea how NHibernate separate config for value object like EntityFramework . I ... | internal class EmployeeConfiguration : ClassMap < Employee > { public EmployeeConfiguration ( ) { Table ( `` Employees '' ) ; Id ( emp = > emp.Id ) .GeneratedBy.Identity ( ) ; Component ( emp = > emp.FullName , name = > { name.Map ( ele = > ele.FirstName ) .Column ( `` FirstName '' ) .Length ( 255 ) .Not.Nullable ( ) ;... | Config complex type for value object using NHibernate in C # |
C# | I have something like this : The problem is that the event is only triggered in MyForm and not in the Winform base ? Why is that so , and how can I have the event triggered in WinformBase too ? | public class WinformBase : Winform { public WinformBase ( ) { this.Activated += new System.EventHandler ( this.MyTest1_Activated ) ; } private void MyTest1_Activated ( object sender , EventArgs e ) { MyController.TopFormActivated ( this ) ; } } public class MyForm : WinformBase { public MyForm ( ) { this.Activated += n... | Activated in baseclass not triggered ? |
C# | I ca n't figure this out and I do n't know why . Sorry is this bad question , I have the following interface in VBWhen I implement the interface in C # I get the following error . The constraints for type parameter 'T ' of method ExecuteSQL ( string , bool , params System.Data.SqlClient.SqlParameter [ ] ) must match th... | Public Interface IFoo Sub ExecuteSQL ( sql As String , ParamArray parameters ( ) As SqlParameter ) Sub ExecuteSQL ( sql As String , useTransaction As Boolean , ParamArray parameters ( ) As SqlParameter ) Function ExecuteSQLAsync ( sql As String , ParamArray parameters ( ) As SqlParameter ) As Task Function ExecuteSQLAs... | Unable to implement VB interface in C # because of constraints error |
C# | One of my ( senior ) coworkers does something really strange in his code . Instead of checking a variable for null , he checks for the type . And because null is FooTypeactually returns false , this works.I think this is bad coding and Resharper seems to agree with me . Is there any reason to write the check this way ?... | public class Foo { private string _bar = null ; public string Bar { get { // strange way to check for null return ( _bar is string ) ? _bar : `` '' ; } set { _bar = value ; } } } | Is checking for type instead of null a reasonable choice ? |
C# | I 'm making custom events for C # and sometimes it is n't working.This is how I 'm making the event happen : And these are the event declarations : This works as long as there are methods attached to the events , but if there is n't , it throws a null ref exception . What am I doing wrong ? | private bool isDoorOpen ; public bool IsDoorOpen { get { return isDoorOpen ; } private set { isDoorOpen = value ; DoorsChangeState ( this , null ) ; } } //events public delegate void ChangedEventHandler ( Elevator sender , EventArgs e ) ; public event ChangedEventHandler PositionChanged ; public event ChangedEventHandl... | Question about custom events |
C# | I have summarized my question in following code snippetabove struct is derived from ValueType which contains GetHashCode method . Below is a class version which derives from Object and contains GetHashCode method.I just wanted to know . Is there any difference between these implementations ? | struct Point { public int X ; public int Y ; public Point ( int x , int y ) { this.X = x ; this.Y = y ; } public override int GetHashCode ( ) { return base.GetHashCode ( ) ; } public void PrintValue ( ) { Console.WriteLine ( `` { 0 } , { 1 } '' , this.X , this.Y ) ; } } class Point { public int X ; public int Y ; publi... | What is difference between GetHashCode implemented in Object and ValueType class ? |
C# | Case 1 produces a type mismatch exception . Case 2 works as expected . Does anyone have insight into why ? Or a better way to have converted from Int32 as an object into an Int16 ? Case 1 : Case 2 : | var i = ( Int16 ) ( object ) Int32.Parse ( `` 1 '' ) ; var i = ( Int16 ) Int32.Parse ( `` 1 '' ) ; | Why does the cast operation fail in case 1 but succeed in case 2 ? |
C# | I have a series data in IEnumrable < double > .Let the dummy data be : let my value of Exceedence be 1.5 , so I want to count the number of time my value in series goes above 1.5 ( basically number of times 1.5 constant line cut the graph ) . In above case it will be 3 ( { 1.6-2.51 } , { 2.52-4.5 } , { 2.53-3.5 } ) .I ... | 00011.62.53.52.511.00002.523.56.54.51.21.02.533.5 | Count number of Exceedence in a series |
C# | I have one class with two important functions : SaveSomething ( ) uses the results calculated in DoSomeThing ( ) .the problem is that we must not to call SaveSomething ( ) before DoSomeThing ( ) or if that happens the results are not true results . I mean order of calls are important , this is a problem in maintaining ... | public class Foo { //plenty of properties here void DoSomeThing ( ) { /*code to calculate results*/ } void SaveSomething ( ) { /* code to save the results in DB*/ } } bool resultsAreCalculated = false ; void SaveSomething ( ) { if ( ! resultsAreCalculated ) { DoSomeThing ( ) ; // the resultsAreCalculated = true ; is se... | best practice when order of calls in class are important ? |
C# | I have got file which looks like this : After choosing file in my Form , I read whole file into a single string . Now , I need to find the highest number between these brackets { } . What will be the best solution for that ? I have already solved that , but my solution is n't the best in my opinion . I was thinking abo... | [ ... ] UTS+48 : : : { 7 } : { 8 } + { 9 } 'UTB+454343 : :34343+ { 10 } - { 12 } ' [ ... ] private int GetNumberOfParameters ( string text ) { string temp = File.ReadAllText ( text ) ; string number = String.Empty , highestNumber = String.Empty ; bool firstNumber = true ; for ( int i = 0 ; i < temp.Length ; i++ ) { if ... | The fastest way to find highest number in document |
C# | This very simple example : Produces : Which is not as expected , the parameter i is n't passed correctly . I had thought to use Action < int > to wrap the code but could n't see how I would . I do not want to write a dedicated method like Task CreateTask ( int i ) I 'm interested how to do it using lambdas.What is norm... | int numLanes = 8 ; var tasks = new List < Task > ( ) ; for ( var i = 0 ; i < numLanes ; ++i ) { var t = new Task ( ( ) = > { Console.WriteLine ( $ '' Lane { i } '' ) ; } ) ; tasks.Add ( t ) ; } tasks.ForEach ( ( t ) = > t.Start ( ) ) ; Task.WaitAll ( tasks.ToArray ( ) ) ; Lane 8Lane 8Lane 8Lane 8Lane 8Lane 8Lane 8Lane ... | Run same code multiple times in parallel with different parameter |
C# | I 've been reading the MSDN page on delegates and they seem straightforward . Then I was looking at some code that uses them and I saw this : It 's that third line that confuses me . How can you new a delegate ? It is not an object , it 's a method , or rather a delegate to a method . According to the example on the MS... | public delegate void NoArguments ( ) ; public NoArguments Refresh = null ; Refresh = new NoArguments ( Reset ) ; | What is this delegate method doing ? |
C# | I have a simple loop which should look like thisunfortunately sbyte.MaxValue +1 = sbyte.MinValue so this never meets the ending condition . My workaround was using int from -128 to 127 but is there also a native sbyte approach ? | for ( sbyte i = sbyte.MinValue ; i < = sbyte.MaxValue ; i++ ) { Console.WriteLine ( i ) ; } | Iterating from MinValue to MaxValue with overflow |
C# | In a performance sensitive program , I am attempting to explicitly call IEquatable < T > .Equals ( ) and not Object.Equals ( to avoid boxing in my case ) . Despite my best efforts , the compiler is always choosing Object.Equals ( ) instead - which I do n't understand . A contrived example class : Equally contrived code... | class Foo : IEquatable < Foo > { public bool Equals ( Foo f ) { Console.WriteLine ( `` IEquatable.Equals '' ) ; return true ; } public override bool Equals ( object f ) { Console.WriteLine ( `` Object.Equals '' ) ; return true ; } } // This calls IEquatable < Foo > Foo f = new Foo ( ) ; f.Equals ( f ) ; // This calls O... | Compiler picking wrong overload calling IEquatable < T > .Equals |
C# | I am calling an externally provided COM DLL for which I have generated a COM interop wrapper . For the sake of argument , let 's call the interface I want to call IEnumFoo.IEnumFoo has the typical COM enumerator pattern : where the first parameter is the number of desired results , the second parameter is a buffer to w... | HRESULT Next ( ULONG celt , IFoo** rgelt , ULONG* pceltFetched ) ; void Next ( uint , out IFoo , out uint ) | What 's the proper way of calling COM enumerators in .NET ? |
C# | I 've been struggling to understand what 's going on with a method I 've got to understand for my test , I 'm having a hard time figuring out the reason I 'm getting the results I get , any explanation on how the `` f '' method works it 's greatly appreciatedLet me explain what I did understand , b.y gets created as an... | class Program { static void Main ( string [ ] args ) { A b = new A ( ) ; b.y = b.x ; b.f ( b.y ) ; b.g ( ) ; Console.WriteLine ( b.x [ 0 ] + `` `` + b.x [ 1 ] ) ; // Prints 1 7 Console.WriteLine ( b.y [ 0 ] + `` `` + ( b.x [ 1 ] + b.y [ 1 ] ) ) ; // 1 14 } } public class A { public int [ ] x = { 1 , 2 } ; public int [ ... | C # confusing method |
C# | I have a situation and I am weak at SQL . Here it is.I have archived items , that are stored with a number . It is like this in the database table.This is how it looks when first inserted . But after deleting , take Number 3 is deleted , It is now like this on DB.3 is gone but what I need is this.The numbers should be ... | RowId Number CaseId234 1 787235 2 787236 3 787237 4 787238 5 787 RowId Number CaseId234 1 787235 2 787 237 4 787238 5 787 RowId Number CaseId234 1 787235 2 787 237 3 787238 4 787 | SQL update a column that lost order ? |
C# | I came across something interesting that I ca n't seem to find any more information on , or a proper name for.I think most of us are aware that if you have multiple using blocks , you only need to include brackets after the last using : However , goofing around I found that the following code also works , without brack... | using ( FileStream fileStream = new FileStream ( zipFilePath , FileMode.Open ) ) using ( ZipInputStream zipStream = new ZipInputStream ( fileStream ) ) { //stuff } using ( BinaryWriter br = new BinaryWriter ( context.Response.OutputStream ) ) while ( true ) { //stuff } | optional nesting ? What is this language feature called , and is it intended ? |
C# | Assuming I am designing a collection of objects for use by others and assuming I have read and understood ( huh ? ) most threads about the differences between operator== and Equals ( ) , WHY should I ever implement operator== ? Stealing an example from this thread , using it can be quite error prone : So , can I tell m... | object x = `` hello '' ; object y = ' h ' + `` ello '' ; // ensure it 's a different reference ( x == y ) ; // evaluates to FALSEstring x = `` hello '' ; string y = ' h ' + `` ello '' ; // ensure it 's a different reference ( x == y ) ; // evaluates to TRUE | Even if I know how/when to overload operator== , WHY should i do it ? |
C# | Is there a problem with checking the conditions for Depleted and raising that event if necessary within the UnitCountChanged event , or should I be doing both in the UnitCount setter ( and anywhere else in a non-trivial example ) ? | public class Basket { private int _unitCount ; public int UnitCount { get { return _unitCount ; } set { _unitCount = Math.Max ( 0 , value ) ; OnUnitCountChanged ( new EventArgs ( ) ) ; } } public event EventHandler UnitCountChanged ; public event EventHandler Depleted ; protected virtual void OnUnitCountChanged ( Event... | Is it smelly to raise an event from within another event ? |
C# | I was going through some C # code and came upon this line : What exactly does the ( - ) do ? ? What would be another way to write this if there is one ? | Matrix [ i , j ] = Convert.ToInt32 ( grab [ i , j ] - ' 0 ' ) ; | ( - ) Symbol Used in Convert Method |
C# | Suppose I have this number list : Keeping the list items in the same order , is it possible to group the items in linq that are sum of 6 so results would be something like this : | List < int > nu = new List < int > ( ) ; nu.Add ( 2 ) ; nu.Add ( 1 ) ; nu.Add ( 3 ) ; nu.Add ( 5 ) ; nu.Add ( 2 ) ; nu.Add ( 1 ) ; nu.Add ( 1 ) ; nu.Add ( 3 ) ; 2,1,3 - 5 - 2,1,1 - 3 | Group items by total amount |
C# | We have a line of code : Which ran at 2:00 on the morning of the 29th of March 2015 in the UK . The returned value was 1:59 , however because of the transition to summer time 1:59 did n't actually happen and caused exceptions further down the line.In my opinion this is a bug in .NET however in lieu of getting a fix to ... | DateTime.Now.AddMinutes ( -1 ) ; if ( ! theDate.IsValidInTimezone ( TimeZoneInfo.Local ) ) { // the time is not valid } | How to determine if the values in a DateTime are valid ? |
C# | Reference : nhibernate criteria for selecting from different tablesI tried to retrieve e.g . last 5 orders but I got the last 5 units ! Which changes are needed to get the units of the last 5 orders ? Thx | Model.Order orderAlias = null ; Model.Unit unitsAlias = null ; Model.Employee employeeAlias = null ; IList < Model.Unit > itemList = null ; using ( m_hibernateSession.BeginTransaction ( ) ) { var query = m_hibernateSession.QueryOver < Model.Unit > ( ( ) = > unitsAlias ) .JoinAlias ( ( ) = > unitsAlias.OrderRef , ( ) = ... | Retrieve the units of the last 5 orders |
C# | I ca n't think of an instance where a protected method should behave differently than a private method in a sealed class.And yet : | public abstract class Base { protected abstract void Foo ( ) ; } public sealed class Derived : Base { // Error CS0507 : can not change access modifiers when // overriding 'protected ' inherited member // public override void Foo ( ) { } // Error CS0621 : virtual or abstract members can not be private // private overrid... | In this case , is the compiler REALLY forcing me to use protected in a sealed class ? |
C# | I inherited a code base that was n't well thought out , and am running into some circular reference problems . My team does n't currently have the time or resources to do a huge refactor , so I was wondering if there was some switch that I could flip that says `` build these two dlls atomically . `` A simplified exampl... | DLL D0 : class A1 - > References B1 class B1 - > References A1 DLL D1 : class A1 - > References D2.B1DLL D2 : class B1 - > References D1.A1 | Are there any hacks to resolve circular reference problems ? |
C# | A third-party generated proxy that we use exposed the BLOB data type as a byte [ ] , and we then expose this value through code generation as follows : This property is then used througout our application ( potentially in different assemblies ) . According to the FxCop rules , properties should n't be exposing arrays .... | public byte [ ] FileRawData { get { return internalDataRow.FileRawData ; } set { this.internalDataRow.FileRawData = value ; } } | Passing a byte [ ] around |
C# | I have an extension method : if I use it and then do something like this : then resharper warns me that there is a possible null reference exception.I know this is not possible , but how can I tell resharper that this is ok ? | public static bool Exists ( this object toCheck ) { return toCheck ! = null ; } if ( duplicate.Exists ( ) ) throw new Exception ( duplicate ) ; | How can I get resharper to know that my variable is not null after I have called an extension method on it ? |
C# | Say I have the following three classes/interfaces : As TestImportViewModel implements IImportViewModel , why will the following not compile ? I understand what the error message `` Can not implicitly convert type 'ValidationResult ' to 'ValidationResult ' '' means . I just do n't understand why this is the case . Would... | public interface IImportViewModel { } public class TestImportViewModel : IImportViewModel { } public class ValidationResult < TViewModel > where TViewModel : IImportViewModel { } ValidationResult < IImportViewModel > r = new ValidationResult < TestImportViewModel > ( ) ; | Why can this generic type not be converted ? |
C# | I 'd like to retrieve an integer value in a SQL Select but only when the data changes , e.g . : Table data : Now I 'd like to get this data : Executing a distinct query , this would not work for me because it would retrieve : Any ideas ? I 'm working with Entity Framework and C # , so suggestions using them would also ... | 50 50 50 52 50 30 30 35 30 30 60 65 60 60 50 52 50 30 35 30 60 65 60 50 52 30 35 60 65 | SQL Select when data changes |
C# | I created a custom List class that maintains a set of item ids for performance reasons : I want to deserialize this List from a simply JSON array e.g . : this will cause JSON.NET to call only the empty constructor , so my itemIDs list remains empty . Also the Add method is not called.How does JSON.NET add the items to ... | public class MyCustomList : List < ItemWithID > { private HashSet < int > itemIDs = new HashSet < int > ( ) ; public MyCustomList ( ) { } [ JsonConstructor ] public MyCustomList ( IEnumerable < ItemWithID > collection ) : base ( collection ) { itemIDs = new HashSet < int > ( this.Select ( i = > i.ID ) ) ; } public new ... | Deserialize to custom list |
C# | I keep using the function below in my classes and would like to write it as generics.I scratch the code below but did n't workPlease advise . Thank you ! | public static IEnumerable < MyObject > Get ( string csvFile ) { return csvFile .ReadAsStream ( ) .SplitCrLf ( ) .Where ( row = > ! string.IsNullOrWhiteSpace ( row ) ) .Select ( row = > new MyObject ( row.Split ( ' , ' ) ) ) ; } public static IEnumerable < T > Get < T > ( string csvFile ) { return csvFile .ReadAsStream ... | Generics basic usage |
C# | I have a struct called MyType that implements IEquatable < MyType > . I have implemented operator == ( MyType x , MyType y ) , but should I also implement operator == ( MyType x , object y ) for the case below ? For example : Usage : | public static bool operator == ( MyType x , object y ) { if ( y is MyType ) { return x == ( MyType ) y ; } return false ; } var a = new MyType ( ) ; object b = new MyType ( ) ; var result = ( a == b ) ; // ? | Should I override == for object and MyType ? |
C# | ( Entity Framework 6 , .NET 4 , VS 2010 ) I have created a small Blog project to illustrate the problem . This is a Blog that has many posts but only one of the posts act as the main post.If I remove the navigation property public virtual Post MainPostEntity everything works as expected . However , when I add it , I ge... | public class Blog { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Post > PostEntities { get ; set ; } public int ? MainPostId { get ; set ; } [ ForeignKey ( `` MainPostId '' ) ] public virtual Post MainPostEntity { get ; set ; } // Problem here } public class Post { publi... | Entity Framework 1-To-* and 1-to-1 |
C# | I have an delegate that looks like this : And an event that looks like this : Is there some easy way to create an IObservable sequence for this event ? I 'd like to do something like this ( but it does n't compile ) : ... . | public delegate void MyDelegate ( int arg1 , int arg2 ) ; public event MyDelegate SomethingHappened ; var obs = Observable.FromEventPattern < int , int > ( this , `` SomethingHappened '' ) ; var subscription = obs.Subscribe ( x , y = > DoSomething ( x , y ) ) ; private void DoSomething ( int value1 , int value2 ) { ...... | How to convert an event to an IObservable when it does n't conform to the standard .NET event pattern |
C# | I usually perform guard checking like so : I 've seen this extra check which ensures that the predicate is actually a lambda : The ExpressionType enum has many possibilities , but I do n't understand how any of them would apply because I assumed the compiler would only allow a lambda.Q1 : Is there benefit to this ? We ... | public void doStuff ( Foo bar , Expression < Func < int , string > > pred ) { if ( bar == null ) throw new ArgumentNullException ( ) ; if ( pred == null ) throw new ArgumentNullException ( ) ; // etc ... } if ( pred.NodeType ! = ExpressionType.Lambda ) throw new ArgumentException ( ) ; | Guard checking of lambdas |
C# | I have several double type variables who for example are named like this : Hight1 , Hight2 , Hight3 , Hight4 , ... The values are in no order and can be all over the place but the variables are all numbered chronologically.Now I want to access the value of those variables and run some code until some condition is met .... | bool Result = false ; if ( 0,3 + Hight1 > = 2 ) { Result = true ; } else { if ( 0,3 + Hight2 > = 2 ) { Result = true ; } else ... bool result = falsefor ( int i = 1 ; result ! ; i++ ) { if ( 0,3 + ( `` Hight '' + i ) > = 2 ) { result = true ; } } | C # for loop - How do I run the loop body with different variables ? |
C# | I want to get information on an Assembly in my C # application . I use the following : This works perfectly returning information on the calling Assembly.I want to share this functionality with other applications , so I include this in a class in my class library.I reference this class library in multiple applications ... | Assembly.GetCallingAssembly ( ) ; | get information on an assembly |
C# | I experimented today with how the compiler determines the types for numbers declared as var.Why is int the default for any number that is between Int32.MinValue and Int32.MaxValue ? Would n't it be better to use the smallest possible data type to save memory ? ( I understand that these days memory is cheap , but still ... | var a = 255 ; //Type = int . Value = byte.MaxValue . Why is n't this byte ? var b = 32767 ; //Type = int . Value = short.MaxValue . Why is n't this short ? var c = 2147483647 ; //Type = int . Value = int.MaxValue . int as expected.var d = 2147483648 ; //Type = uint . Value = int.MaxValue + 1. uint is fine but could hav... | How does var work for numbers ? |
C# | I have a quick question hopefully about Action types and Lambdas in C # . Here 's come code : If you run this code you will see that it outputs 10 , ten times in a row , then outputs the numbers 0-9 the second time around . It clearly has something to do with the way I use X vs I , and how I give my action a new variab... | static void Main ( string [ ] args ) { List < Action > actions = new List < Action > ( ) ; for ( int I = 0 ; I < 10 ; I++ ) actions.Add ( new Action ( ( ) = > Print ( I.ToString ( ) ) ) ) ; foreach ( Action a in actions ) { a.Invoke ( ) ; } actions.Clear ( ) ; int X ; for ( X = 0 ; X < 10 ; X++ ) { int V = X ; actions.... | C # object references and Action types |
C# | I am looking for a way to dynamically build an expression , based upon the method parameters.This is the code snippet from my service method , where I would like to build a predicate expression.GetWhereAsync is a method from the generic repository that looks like : And Parameters class : What I would like to implement ... | public async Task < Account > GetCustomerAccountsAsync ( Parameters params ) { var items = await _unitOfWork.Accounts.GetWhereAsync ( a = > a.CustomerId == params.CustomerId & & ... ) ; ... } public async Task < IEnumerable < TEntity > > GetWhereAsync ( Expression < Func < TEntity , bool > > predicate ) { return await ... | every Parameter object property that is not null , to be added to expression predicate as a condition |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.