lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have a model which has is below and when I add ComboProducts object with the linq below I am getting the error . Is there something I am missing in this code ? Errorappears in two structurally incompatible initializations within a single LINQ to Entities query . A type can be initialized in two places in the same que... | public class Product { public int ProductId { get ; set ; } public string Name { get ; set ; } public List < Product > ComboProducts { get ; set ; } } ListOfProducts = ( from p in db.Products join ptp in db.ProductToProducts on p.ProductId equals ptp.ParentProductId join pr in db.Pricings on ptp.ProductToProductId equa... | Error with two structurally incompatible initializations within a single LINQ |
C# | I am using .Replace ( ) method to replace a placeholder [ CITY ] in arabic language.I get the following output As you can see the city instead of being placed next to ABC is added at the extreme right.This issue happens only for arabic and works fine for other languages ( english/thai/spanish etc ) Not sure whats going... | public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; var replace = `` سنغافورة '' ; var input = `` ABC [ CITY ] مرحبا بالعالم '' ; Console.WriteLine ( input ) ; var final = input.Replace ( `` [ CITY ] '' , replace ) ; Console.WriteLine ( final ) ; } ABC [ CITY ] مرحبا بالعالمABC سنغافورة مرحبا بالعال... | C # .Replace ( ) method does not work correctly with Arabic language |
C# | Is there any point in doing this ? ... as supposed to this : Setting aside the obvious null dereference possibility , If I where to write a lot of value types using this method would n't the former be much better because it will have it 's own version of the write method to call , or is it just gon na bloat the binary ... | public static void Write < T > ( T value ) { textWriter.Write ( value.ToString ( ) ) ; } public static void Write ( object value ) { textWriter.Write ( value.ToString ( ) ) ; } | Boxing , a thing of the past ? |
C# | My question is simple , why GC ca n't figure it out that timer object in the main should be garbage collected along with the timer inside TestTimer and associated EventHandler ? Why am I continously getting console.Writeline output ? | class Program { public static void Main ( ) { TestTimer timer = new TestTimer ( ) ; timer = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.ReadKey ( ) ; } } public class TestTimer { private Timer timer ; public TestTimer ( ) { timer = new Timer ( 1000 ) ; timer.Elapsed += new ElapsedEventHandler ( ti... | Why ca n't GC figure it out ? |
C# | I am not a Java programmer . I read the documentation on `` final '' , and understand it to mean `` a variable 's value may be set once and only once . `` I am translating some Java to C # . The code does not execute as expected . I tried to figure out why , and found some uses of final that do n't make sense.Code snip... | final int [ ] PRED = { 0 , 0 , 0 } ; ... PRED [ 1 ] = 3 ; final int [ ] PRED = new int [ this.Nf ] ; for ( int nComponent = 0 ; nComponent < this.Nf ; nComponent++ ) { PRED [ nComponent ] = 0 ; } ... PRED [ 1 ] = 3 ; | Understanding Java 's `` final '' for translation to C # |
C# | I have this method : What I would like to do is to delete from three tables that are here : Is there a delete function in EF6 that I can use to delete all the rows or should I somehow make a SQL call ? | [ Route ( `` Delete '' ) ] public IHttpActionResult Delete ( ) { } public System.Data.Entity.DbSet < SampleSentence > SampleSentences { get ; set ; } public System.Data.Entity.DbSet < Synonym > Synonyms { get ; set ; } public System.Data.Entity.DbSet < WordForm > WordForms { get ; set ; } | How can I delete rows from tables using EF when inside an Asp.Net method ? |
C# | BackgroundI have a couple of utility methods I would like to add to a solution on which I am working and use of dependency injection would open many more potential uses of said methods.I am using C # , .NET 4Here is an example of what I am trying to accomplish ( this is just an example ) : What I have done here is crea... | public static void PerformanceTest ( Func < ? ? ? > func , int iterations ) { var stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; for ( int i = 0 ; i < iterations ; i++ ) { var x = func ( ) ; } stopWatch.Stop ( ) ; Console.WriteLine ( stopWatch.ElapsedMilliseconds ) ; } Utilities.PerformanceTest ( someObject.Some... | How do I write a C # method that will accept an injected dependency of unknown type ? |
C# | This is normal LINQ , and this Test succeeds : But when you insert the data into a database and try to do the same when using LINQ to Entities , it seems like the resulting SQL is the same , regardless of the sorting you apply.Can somebody please help me ? - > Please show me how to keep my sorting when grouping when us... | using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Collections.Generic ; using System.Linq ; namespace TestLINQ.Tests { [ TestClass ] public class UnitTest2 { [ TestMethod ] public void TestGroupingAndOrdering ( ) { var persons = GetTestPersons ( ) ; //Try get oldest Man and oldest Woman .... | LINQ versus LINQ to Entities , keep Sorting when Grouping |
C# | I 'm using Entity Framework 4 along with MSSQL to store and access data on my Windows Forms application.Here is an example class I use to access data : And here 's an example of how I use it.Someone suggested that I use IDisposable to properly `` clean up '' the connection , but I do n't know how to implement this . An... | public class StudentRepository : IDisposable { ColegioDBEntities db = new ColegioDBEntities ( ) ; public IQueryable < Student > FindAllStudents ( ) { return db.Students ; } public Student FindStudent ( int id ) { return db.Students.SingleOrDefault ( c = > c.StudentId == id ) ; } public void Add ( Student Student ) { db... | How would I implement IDisposable in this context ? |
C# | Is it possible to write the folowing using lambda ( C # ) | private static void GetRecordList ( List < CustomerInfo > lstCustinfo ) { for ( int i = 1 ; i < = 5 ; i++ ) { if ( i % 2 == 0 ) lstCustinfo.Add ( new CustomerInfo { CountryCode = `` USA '' , CustomerAddress = `` US Address '' + i.ToString ( ) , CustomerName = `` US Customer Name '' + i.ToString ( ) , ForeignAmount = i ... | Rewriting a statement using LINQ ( C # ) |
C# | I have an abstract Model and an implementationMy coins object does not show `` Coins '' as its label in my view when I use Html.LabelFor on it , it shows `` Label '' . If I move the DisplayName attribute into Treasure , it works ... but I need to be able to change the label for different implementations of the Treasure... | public abstract class Treasure { public abstract int Value { get ; } public abstract string Label { get ; } } public class Coins : Treasure { [ DisplayName ( `` Coin Value '' ) ] public override int Value { get { ... } } [ DisplayName ( `` Coins '' ) ] public override string Label { get { ... } } | MVC Attributes on abstract properties |
C# | Since I do n't have much reputation to post image , I am elaborating as a big question.I have three windows forms in which the execution of events get increased each time the form is created.1 . Form1 ( MainForm ) Here I call the second form ( SubForm ) which contains a user control . 2 . Form2 ( SubForm ) Here I call ... | private void button1_Click ( object sender , EventArgs e ) { SubForm obj = new SubForm ( ) ; obj.ShowDialog ( ) ; } // Event generationUserControl1.MouseUp += new EventHandler ( this.Node_Click ) ; // Event that calls the ChildForm private void Node_Click ( object sender , EventArgs e ) { ChildForm obj = new ChildForm ... | How do I restrict events firing more than once at a time |
C# | I have a XML file that contains multiple < p > tags in it . Some of the < p > tags contain < br/ > in it . So , I am supposed to create a new XElement for each < br/ > in the tag . I have tried to achieve by reading each line using foreach and replacing each < br/ > with < /p > + Environment.NewLine + < p > .It works b... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE repub SYSTEM `` C : \repub\Repub_V1.dtd '' > < ? xml-stylesheet href= '' C : \repub\repub.xsl '' type= '' text/xsl '' ? > < repub > < head > < title > xxx < /title > < /head > < body > < sec > < title > First Title < /title > < break name= '' 1-1 '' / > <... | How do I replace multiple < br/ > tags with a specific element in a new line ? |
C# | I 've encounter a weird problem with C # threading.This is my sample program using thread to `` activate '' the Print ( ) function at each agent in the agentList.And here is the result when I run the above program : But what I expected is something contains all 4 agents likeThe most amazing thing is that if I called th... | class Program { static void Main ( string [ ] args ) { List < Agent > agentList = new List < Agent > ( ) ; agentList.Add ( new Agent ( `` lion '' ) ) ; agentList.Add ( new Agent ( `` cat '' ) ) ; agentList.Add ( new Agent ( `` dog '' ) ) ; agentList.Add ( new Agent ( `` bird '' ) ) ; foreach ( var agent in agentList ) ... | Weird Threading with C # |
C# | I 've noticed a difference in the way the C # 8.0 compiler builds closure classes for captured IDisposable variables that are declared with a C # 8.0 using declaration , as opposed to variables declared with the classic using statement.Consider this simple class : And this sample code : The compiler generates this code... | public class DisposableClass : IDisposable { public void Dispose ( ) { } } public void Test ( ) { using var disposable1 = new DisposableClass ( ) ; using var disposable2 = new DisposableClass ( ) ; Action action = ( ) = > Console.Write ( $ '' { disposable1 } { disposable2 } '' ) ; } [ CompilerGenerated ] private sealed... | Why are closures different for variables from C # 8.0 using declarations ? |
C# | Given the following program : Which produces the following output : I chose to use dynamic here to avoid the following : using switch/if/else statements e.g . switch ( foo.GetType ( ) .Name ) explicit type checking statements e.g . foo is Foo1explicit casting statements e.g . ( Foo1 ) fooBecause of the dynamic conversi... | using System ; using System.Collections.Generic ; namespace ConsoleApplication49 { using FooSpace ; class Program { static void Main ( string [ ] args ) { IEnumerable < FooBase > foos = FooFactory.CreateFoos ( ) ; foreach ( var foo in foos ) { HandleFoo ( foo ) ; } } private static void HandleFoo ( FooBase foo ) { dyna... | Using dynamic to set disparate properties of uncontrolled ( third party ) sealed types |
C# | I 've got a class with readonly fields that indicate the state of my object . These fields should be visible from the outside.At first I showed these fields with properties like this : But as this is readonly , users of my class ca n't change the instance of the state . Therefore , I removed my property , set the reado... | public class MyClass { private readonly MyState mystate = new MyState ( ) ; public MyState MyState { get { return this.mystate ; } } } | Can readonly fields be public ? |
C# | Consider the following : I am able fill dictionary manually . However is it possible add it dynamically ? How I may convert generic method to Func ? | public interface ISomething { string Something ( ) ; } public class A : ISomething { public string Something ( ) { return `` A '' ; } } public class B : ISomething { public string Something ( ) { return `` B '' ; } } public class Helper { private static readonly Dictionary < string , Func < string , string > > Actions ... | How to populate dictionary of Func < T > dynamically |
C# | I 'm converting a project from Java to C # . I 've tried to search this , but all I come across is questions about enums . There is a Hashtable htPlaylist , and the loop uses Enumeration to go through the keys . How would I convert this code to C # , but using a Dictionary instead of a Hashtable ? | // My C # Dictionary , formerly a Java Hashtable.Dictionary < int , SongInfo > htPlaylist = MySongs.getSongs ( ) ; // Original Java code trying to convert to C # using a Dictionary.for ( Enumeration < Integer > e = htPlaylist.keys ( ) ; e.hasMoreElements ( ) ; { // What would nextElement ( ) be in a Dictonary ? SongInf... | Converting Enumeration < Integer > for loop from Java to C # ? What exactly is an Enumeration < Integer > in C # ? |
C# | I have a small issue with visual studio.I have a method that throws a CustomExceptionIf I wrap the code that calls this method in a try/catch I can see the exception details in the debuggerif I remove the try/catch I can see that the `` errors '' property has Count=4 but I can not see the errors ... Is this expected or... | using System ; using System.Collections.Generic ; using System.Linq ; namespace ClassLibrary1 { public static class Class1 { public static void DoSomethingThatThrowsException ( ) { throw new MyException ( Enumerable.Range ( 1 , 4 ) .Select ( e = > new MyError ( ) { Message = `` error `` + e.ToString ( ) } ) .ToList ( )... | View Detail window does not expand Collection properties |
C# | I 'm trying to create a program that parses data from game 's chat log . So far I have managed to get the program to work and parse the data that I want but my problem is that the program is getting slower.Currently it takes 5 seconds to parse a 10MB text file and I noticed it drops down to 3 seconds if I add RegexOpti... | if ( sender.Equals ( ButtonParse ) ) { var totalShots = 0f ; var totalHits = 0f ; var misses = 0 ; var crits = 0 ; var regDmg = new Regex ( @ '' ( ? < =\bSystem\b . * You inflicted ) \d+.\d '' , RegexOptions.Compiled ) ; var regMiss = new Regex ( @ '' ( ? < =\bSystem\b . * Target evaded attack ) '' , RegexOptions.Compi... | Regular Expressions slowing down the program |
C# | I have array of strings and I have to add hyperlink to every single match of item in array and given string.Principally something like in Wikipedia.Something like : string p = `` The Domesday Book records the manor of Greenwich as held by Bishop Odo of Bayeux ; his lands were seized by the crown in 1082 . A royal palac... | private static string AddHyperlinkToEveryMatchOfEveryItemInArrayAndString ( string p , string [ ] arrayofstrings ) { } arrayofstrings = { `` Domesday book '' , `` Odo of Bayeux '' , `` Edward '' } ; | How to make programmatically html text with hyperlinks like in Wikipedia ? |
C# | This is the example : but it says acnnot convert Anonymous type # 1 to FotoLiveLove . | public class FotoLiveLove { public string Tipologia { get ; set ; } public string URL { get ; set ; } } IList < FotoLiveLove > fotoLiveLove = xDoc [ `` statuses '' ] .Select ( x = > new { Tipologia = `` twitter '' , URL = ( string ) x [ `` URLJSON '' ] } ) .ToList ( ) ; | Can I populate a list of my own class directly in LINQ ? |
C# | Is there a way to specify that a generic type be of one type or another type ? | public class SoftDrink < T > where T : TypeOne or TypeTwo { } | Specify a C # Generic Constraint to be of ClassA OR ClassB ? |
C# | I take user input on a form and bind it to a parameter which will then tie to my report . Can I use a single collection to hold all of my parameters ? It seems redundant to have to create a collection and a parameter for every item I want to pass to my report . To make this work the way I require , I 've had to add a c... | // # 1 Setup a collections ParameterValues firstNameCollection = new ParameterValues ( ) ; ParameterValues lastNameCollectoin = new ParameterValues ( ) ; // # 2 Set the parameters ParameterDiscreteValue firstNameParam = new ParameterDiscreteValue ( ) ; ParameterDiscreteValue lastNameParam = new ParameterDiscreteValue (... | Use a single collection to hold all parameters |
C# | I have some client code that sends date in the following format `` 1/31/2013 11:34:28 AM '' ; I am trying to cast it into DateTime objectthis throws String was not recognized as a valid DateTime.how can i cast it ? | string dateRequest = `` 1/31/2013 11:34:28 AM '' ; DateTime dateTime = DateTime.Parse ( dateRequest ) ; | DateTime.Parse throws exception when parsing string |
C# | The following program will print the fields and whether the are constant or not using IsLiteralIt works correctly for all types , except for decimal is will return false.Can anyone explain this behavior ? And is there a better way to see if a field is constant ? | public static class Program { public static void Main ( string [ ] args ) { foreach ( var field in typeof ( Program ) .GetFields ( ) ) { System.Console.WriteLine ( field.Name + `` IsLiteral : `` + field.IsLiteral ) ; } System.Console.ReadLine ( ) ; } public const decimal DecimalConstant = 99M ; public const string Stri... | Why does IsLiteral return false for decimal ? |
C# | I work with multethreading bug . Now I see that for some reason lock is n't executed even once but is locked . I have the next class : I paused all threads in the VS , inspected all of them and see that there is only one thread in the SomeMethod and it is waiting for lock ( _lock ) to be freed ( _inCnt = 0 ) .I resumed... | public sealed class Foo { private readonly object _lock = new object ( ) ; private static ulong _inCnt = 0 ; public void SomeMethod ( ulong poo ) { lock ( _lock ) { _inCnt++ ; ... [ some code ] } } } | Corrupted lock ? Magic deadlock ? |
C# | I 'm aware of technique to handle IDisposable in a traditional manner . Say , in OnStop ( ) method of windows service I close message queue client : For the first time today I saw one guy doing that this way : What is exactly happening inside his `` using '' or does he dispose correctly at all ? | if ( client ! = null ) { client.Dispose ( ) ; } using ( client ) { client = null ; } | Disposing by setting to null ? |
C# | I 've an XML file such as below : For some reasons , I need to create child and nested nodes from the Element node attributes.The output that I want is : How can i do it ? Or any idea , reference , article ... Thanks . | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LayoutControl ID= '' rootlyt '' Type= '' LayoutControl '' > < LayoutGroup ID= '' lgp8 '' Header= '' PersonalInfo '' IsCollapsed= '' False '' IsLocked= '' False '' Orientation= '' Vertical '' View= '' GroupBox '' HorizontalAlignment= '' Left '' VerticalAlignment= ''... | Convert inline XML node to nested nodes in asp.net using c # |
C# | I 'm just curious how .NET defines a process architectural interface if I compile the source code under `` Any CPU '' configuration setting . I always thought that if you run that process in a x64 computer , it will be a 64-bit process . However , the example below shows a totally different thing.I have a simple consol... | static void Main ( string [ ] args ) { Console.WriteLine ( `` Process Type : { 0 } '' , Environment.Is64BitProcess ? `` 64 Bit '' : '' 32 Bit '' ) ; Console.ReadLine ( ) ; } | How does .NET define a process architectural interface ? |
C# | I 'm working on modifying Roslyn , and in this file I come across this code : Following the reference to specializedMethodReference.UnspecializedVersion gets me to this file , and this code : I 've read those comments three times , and I 've done a bit of Googling , and I have no idea what they 're talking about . Coul... | ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference ; if ( specializedMethodReference ! = null ) { methodReference = specializedMethodReference.UnspecializedVersion ; } /// < summary > /// Represents the specialized event definition./// < /summary > internal interface I... | What are specialized events , fields , methods and properties ? |
C# | I must be reinventing the wheel here - but I 've searched and I ca n't find anything quite the same ... Here 's my code for creating a sequence of zero or more objects that have a default constructor : My question is quite simple : Is there a Linq equivalent of this I should be using ? | public static IEnumerable < T > CreateSequence < T > ( int n ) where T : new ( ) { for ( int i = 0 ; i < n ; ++i ) { yield return new T ( ) ; } } | Linq method for creating a sequence of separate objects ? |
C# | In the following C # snippet I override the == method . _type is a number of type short . So I 'm actually saying that two WorkUnitTypes are the same when those two shorts are the same.Because R # warns me , and it is totally clear why , that type1/type2 could potentially be null I 'm trying to catch that with the if s... | public static bool operator == ( WorkUnitType type1 , WorkUnitType type2 ) { if ( type1 == null || type2 == null ) return false ; return type1._type == type2._type ; } | Check for null in == override |
C# | BackgroundI have a convenience class which is essentially a dictionary that holds a tag/value pair list for submission to an API.At its very basic level all I did is this : This maps well to the needs of the API , since the whole thing gets sent and parsed as a string . However , it 's not so great for the caller ; for... | enum Tag { Name , Date , //There are many more } class RequestDictionary : Dictionary < Tag , string > { } enum Tag { Name , Date } interface ITags { string Name { get ; set ; } DateTime Date { get ; set ; } } class RequestDictionary : Dictionary < Tag , string > , ITags { public ITags Tags { get { return this ; } } st... | Use object initializer syntax with an interface |
C# | This only happens on a Windows 8.1+ touch device . I have some panels where the user can slide around with their finger . I have implemented PreFilterMessage so that I can catch the mouse move globally throughout the application without having to worry about child controls interfering.I sometimes receive the generic er... | IsCanceledMove ( ) Object reference not set to an instance of an object . private static void mouseFilter_MouseFilterMove ( object sender , MouseFilterEventArgs e ) { IsCanceledMove ( sender as Control ) ; } public bool PreFilterMessage ( ref Message m ) { Point mousePosition = Control.MousePosition ; var args = new Mo... | How can a mouse event sender be null ? ( Only on Windows 8.1+ TOUCH ) |
C# | I understand that async which awaits a task yields execution back to the caller , allowing it to continue until it needs the result.My interpretation of what I thought would come out of this was correct up until a certain point . It looks as though there 's some sort of interleaving going on . I expected Do3 ( ) to com... | await this.Go ( ) ; async Task Go ( ) { await Do1 ( async ( ) = > await Do2 ( `` Foo '' ) ) ; Debug.WriteLine ( `` Completed async work '' ) ; } async Task Do1 ( Func < Task > doFunc ) { Debug.WriteLine ( `` Start Do1 '' ) ; var t = Do2 ( `` Bar '' ) ; await doFunc ( ) ; await t ; } async Task Do2 ( string id ) { Debug... | Can exiting an async method yield control back to a different async method ? |
C# | Today I have taken a look at the implementation of the Thumb control in order to learn how it works . What struck me is , that there are 3 methods which seem to override internal virtual parent methods , namelyI am not so much interested in what these methods do specifically , but rather what could be valid reasons to ... | internal override int EffectiveValuesInitialSize { get ; } internal override DependencyObjectType DTypeThemeStyleKey { get ; } internal override void ChangeVisualState ( bool useTransitions ) ; | Why do WPF shipped classes have internal virtual methods ? |
C# | My code : At times my application will stop at the cpuLabel invoke and throw an `` ArgumentOutOfRangeException '' when it was handled and fixed in my code . I tried increasing the timer that activates the thread that activates CPUStats ( ) , but to no avail . Why would this happen ? | public void CPUStats ( ) { var cpuCounter = new PerformanceCounter ( `` Processor '' , `` % Processor Time '' , `` _Total '' ) ; var ramCounter = new PerformanceCounter ( `` Memory '' , `` Available MBytes '' ) ; ramCounter.NextValue ( ) ; cpuCounter.NextValue ( ) ; System.Threading.Thread.Sleep ( 1000 ) ; string cpusa... | Exception that is handled is still thrown ? |
C# | If I have an event like this : And adds an eventhandler like this : ... is it then possible to register this somehow ? In other words - is it possible to have something like : | public delegate void MyEventHandler ( object sender , EventArgs e ) ; public event MyEventHandler MyEvent ; MyEvent += MyEventHandlerMethod ; MyEvent.OnSubscribe += MySubscriptionHandler ; | Is it possible to subscribe to event subscriptions in C # ? |
C# | Hi I am developing a chatbot on amazon lex and I want to send a response card using the lambda function but on using response card function inside the close response format it gives the error of null exception . Can anyone tell the solution to it ? PS I am using FlowerOrder blueprint created by Nikki.Exception : -2020-... | if ( slots [ greet ] ! = null ) { var validateGreet = ValidateUserGreeting ( slots [ greet ] ) ; if ( validateGreet.IsValid ) { return Close ( sessionAttributes , `` Fulfilled '' , new LexResponse.LexMessage { ContentType = `` PlainText '' , Content = String.Format ( `` Hello Kindly choose one option '' ) } , new LexRe... | How to send a response card using AWS Lambda in C # |
C# | I want to open the folder where a file had been just saved and select the file , for that I use this little code : It works perfectly.I need to put this code in several places so I decided to create a method , there is also a condition in this method : This does n't work as expected : this opens the parent folder ( of ... | var psi = new ProcessStartInfo ( `` Explorer.exe '' , `` /select , '' + dlg.FileName ) ; Process.Start ( psi ) ; private static void OpenFolderAndSelectMyFile ( string fileName ) { if ( MySettings.Default.openFolder == true ) { var psi = new ProcessStartInfo ( `` Explorer.exe '' , `` /select , '' + fileName ) ; psi.Win... | Open folder issue |
C# | This might be lame , but here : Now I want to create an instance of the ImplementedInterface and initialize it 's members.Can this be done somehow like this ( using initialization lists ) or the same behavior can only be achieved using the constructor with Double argument ? | public interface Interface < T > { T Value { get ; } } public class InterfaceProxy < T > : Interface < T > { public T Value { get ; set ; } } public class ImplementedInterface : InterfaceProxy < Double > { } var x = new ImplementedInteface { 30.0 } ; | C # initialization question |
C# | I have the following class : I have a method that takes in Person and a String as parameters : Since Person was passed by reference , it should change the Name of the passed instance . But is this method more readable than the one above ? | public class Person { public String Name { get ; set ; } } public void ChangeName ( Person p , String name ) { p.Name = name ; } public Person ChangeName ( Person p , String name ) { p.Name = name ; return p ; } | Pass by reference : Which is more readable/right ? |
C# | I have created a new VS 2010 extensibility package . So far , all I want to do is have the user press a button and fill a listview with the entire contents of the solution . I have the following code : This does seem to work , however , it populates the list with the contents of the solution with the package in it and ... | EnvDTE80.DTE2 dte = ( EnvDTE80.DTE2 ) System.Runtime.InteropServices.Marshal . GetActiveObject ( `` VisualStudio.DTE.10.0 '' ) ; foreach ( Project project in dte.Solution.Projects ) { foreach ( ProjectItem pi in project.ProjectItems ) { listView1.Items.Add ( pi.Name.ToString ( ) ) ; } } | Visual Studio Extensibility Package not looking at correct project |
C# | I am a little confused on content equality in reference types specifically . I am not overriding Equality in either case - so why is the behavior different . See 2 simple code examples : Example 1 : Returns TrueExample 2 : Both statements return False | class Program { static void Main ( string [ ] args ) { object o1 = `` ABC '' ; object o2 = `` ABC '' ; Console.WriteLine ( `` object1 and object2 : { 0 } '' , o1.Equals ( o2 ) ) ; } } class Program { static void Main ( string [ ] args ) { Person person1 = new Person ( `` John '' ) ; Person person2 = new Person ( `` Joh... | Equality in Reference Types |
C# | My class structure ( simplified ) Now , having only the type FinalClass1 and FinalClass2 I need to get their respective T types from the Foo interface - SomeClass for FinalClass1 and SomeOtherClass for FinalClass2 . The abstract classes can implement more generic interfaces , but always only one Foo.How can I achieve t... | interface Foo < T > { } abstract class Bar1 : Foo < SomeClass > { } abstract class Bar2 : Foo < SomeOtherClass > { } class FinalClass1 : Bar1 { } class FinalClass2 : Bar2 { } | Generic type from base interface |
C# | I am wanting to find out if there is a way to initialize a List < T > where T is an object much like a simple collection gets initialized ? Simple Collection Initializer : Object Collection Initilizer : The question is , how and if you can do something like this ? | List < int > digits = new List < int > { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; List < ChildObject > childObjects = new List < ChildObject > { new ChildObject ( ) { Name = `` Sylvester '' , Age=8 } , new ChildObject ( ) { Name = `` Whiskers '' , Age=2 } , new ChildObject ( ) { Name = `` Sasha '' , Age=14 } } ; List ... | Object Initializer for object collections |
C# | Hi , I have the following code which produces a strange behaviour.A property of an instance of objects contained in an IEnumerable produced by linq to Objects , does not get updated in subsequent foreach statements . The foreach statement should enuemerate the IEnumerable . Instead the solution is to enumerate it befor... | public class MyClass { public int val ; } public class MyClassExtrax { public MyClass v1 { get ; set ; } public int prop1 { get ; set ; } } void Main ( ) { List < MyClass > list1 = new List < MyClass > ( ) ; MyClass obj1 = new MyClass ( ) ; obj1.val = 10 ; list1.Add ( obj1 ) ; MyClass obj2 = new MyClass ( ) ; obj2.val ... | Strange behaviour in linq c # under delayed execution |
C# | I am generating two sets of repeating events in seperate loop iterations but am having a conflict when comparing the generated results for conflicts . This seems to be when the times go backwards and I am unsure how to solve this ? The first repeat event will : repeat everyday at 00:00 to 01:00 in `` Europe/Stockholm '... | String timeZone = `` Europe/Stockholm '' ; for ( ZonedDateTime date_Local = repeatSeriesStartDate_Local ; date_Local < = LoopEndDate_Local ; date_Local = new ZonedDateTime ( Instant.FromDateTimeUtc ( date_Local.ToDateTimeUtc ( ) .AddDays ( 1 ) .ToUniversalTime ( ) ) , timeZone ) ) | How to handle when timezone goes backwards in the future |
C# | For some weird reason , both the System.Runtime.Remoting.Messaging.CallContext and AsyncLocal classes are only available using the full CLR . This makes it really hard to do asynchronous scoping while working with Portable Class Libraries or Windows Phone applications , especially since Windows Phone APIs are becoming ... | private async void button_Click ( object sender , EventArgs e ) { CallContext.LogicalSetData ( `` x '' , new object ( ) ) ; await Something ( ) ; var context = CallContext.LogicalGetData ( `` x '' ) ; } | Implementing asynchronous scoping in PCL and Windows Phone applications |
C# | Sometimes it 's useful to have something like : because X describes both what the type is ( as a class name ) , and the value being accessed/mutated ( as the property name ) . So far so good . Suppose you wanted to do the same thing , but in a generic way : For this example , the compiler complains that : The type ' Z ... | class X { ... } class Y { X X { get { ... } set { ... } } } class Z < T > { T T { get { ... } set { ... } } } class Z < U > { U T { get { ... } set { ... } } } | Why is there a name clash between generic type parameter and other members |
C# | Consider the following code ... In my tests for a RELEASE ( not debug ! ) x86 build on a Windows 7 x64 PC ( Intel i7 3GHz ) I obtained the following results : It seems that using a Func < > to define a delegate to create new objects is more than 6 times faster than calling `` new T ( ) '' directly . I find this slightl... | CreateSequence ( ) with new ( ) took 00:00:00.9158071CreateSequence ( ) with creator ( ) took 00:00:00.1383482CreateSequence ( ) with new ( ) took 00:00:00.9198317CreateSequence ( ) with creator ( ) took 00:00:00.1372920CreateSequence ( ) with new ( ) took 00:00:00.9340462CreateSequence ( ) with creator ( ) took 00:00:... | Why is using a Func < > so much faster than using the new ( ) constraint on a generic sequence creator |
C# | We have our own certificate that we use as part of the ClientCredentials in Transport Client Credentials as seen below.Our partner also provided us with a copy of their certificate that is used on the server in order to validate their server . Calls to the service currently succeed without us having installed or done a... | WSHttpBinding wsBinding = new WSHttpBinding ( ) ; wsBinding.Security.Mode = System.ServiceModel.SecurityMode.Transport ; wsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate ; wsClient = new WSService.WSClient ( wsBinding , new EndpointAddress ( serviceURL ) ) ; wsClient.ClientCreden... | What role does a public certificate play in WCF ? |
C# | I want to create a TCP Listener using Kestrel and the System.IO.Pipelines package . The messages I receive will always be HL7 messages . An example message could beMSH|^~ & |MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5EVN||200605290901||||200605290900PID|||56782445^^^UAReg^PI||... | internal class HL7Listener : ConnectionHandler { public override async Task OnConnectedAsync ( ConnectionContext connection ) { IDuplexPipe pipe = connection.Transport ; await FillPipe ( pipe.Output ) ; await ReadPipe ( pipe.Input ) ; } private async Task FillPipe ( PipeWriter pipeWriter ) { const int minimumBufferSize... | How to create a responding TCP listener with the System.IO.Pipelines package ? |
C# | I have two bytes . I need to turn them into two integers where the first 12 bits make one int and the last 4 make the other . I figure i can & & the 2nd byte with 0x0f to get the 4 bits , but I 'm not sure how to make that into a byte with the correct sign.update : just to clarify I have 2 bytesand I need to do somethi... | byte1 = 0xabbyte2 = 0xcd var value = 0xabc * 10 ^ 0xd ; | Perform signed arithmetic on numbers defined as bit ranges of unsigned bytes |
C# | I really do n't understand why c # compiler allows some useless statements but disallows some other useless statements . | static void Main ( ) { string ( ' a ' , 1 ) ; // useless but allowed // '' a '' ; // useless and disallowed new int ( ) ; // useless but allowed //0 ; // useless and disallowed new char ( ) ; // useless but allowed //'\0 ' ; // useless and disallowed new bool ( ) ; // useless but allowed //false ; // useless and disall... | Why are some useless statements partially allowed ? |
C# | I 'm using Unity to make a game . I have multiple animal enemies in the game.I 'm working on missions inside the game that you have to kill a random number of random animals , this I already have.What I have a problem with is to increase the mission count when you kill an animal.I got a script ( dead ) sitting on each ... | public string Name ; public MissionHolder missionHolder ; public void Kill ( ) { if ( name == `` Tiger '' ) { missionHolder.Tiger += 1 ; } if ( name == `` Hyena '' ) { missionHolder.Hyena += 1 ; } if ( name == `` Gorilla '' ) { missionHolder.Gorilla += 1 ; } if ( name == `` Giraffe '' ) { missionHolder.Giraffe += 1 ; }... | How can I simplify this long series of if statements ? |
C# | I 'm trying to assign a static List < PropertyInfo > of all DbSet properties in the Entities class.However when the code runs the List is empty because .Where ( x = > x.PropertyType == typeof ( DbSet ) ) always returns false.I tried multiple variations in the .Where ( ... ) method like typeof ( DbSet < > ) , Equals ( .... | public partial class Entities : DbContext { //constructor is omitted public static List < PropertyInfo > info = typeof ( Entities ) .getProperties ( ) .Where ( x = > x.PropertyType == typeof ( DbSet ) ) .ToList ( ) ; public virtual DbSet < NotRelevant > NotRelevant { get ; set ; } //further DbSet < XXXX > properties ar... | Linq .Where ( type = typeof ( xxx ) ) comparison is always false |
C# | I 'm working on a VS Extension that needs to be aware of which class member the text-cursor is currently located in ( methods , properties , etc ) . It also needs an awareness of the parents ( e.g . class , nested classes , etc ) . It needs to know the type , name , and line number of the member or class . When I say `... | public static class CodeElementHelper { public static CodeElement [ ] GetCodeElementAtCursor ( DTE2 dte ) { try { var cursorTextPoint = GetCursorTextPoint ( dte ) ; if ( cursorTextPoint ! = null ) { var activeDocument = dte.ActiveDocument ; var projectItem = activeDocument.ProjectItem ; var codeElements = projectItem.F... | VS Extension : TextPoint.GreaterThan / LessThan very slow for large files |
C# | I am trying to Pinvoke the lmdif1 method in the cminpack_dll.dll from c # and i am running into some curious errors . The 2nd and third parameters passed to lmdif1 are ints , and for my test the values in order are 12 and 9 . Now when ther are in the C code , the value that was 12 is now 9 and the value that was 9 vari... | [ DllImport ( `` cminpack_dll.dll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern int lmdif1 ( IntPtr fcn , int m , int n , double [ ] x , double [ ] fVec , double tol , int [ ] iwa , double [ ] wa , int lwa ) ; int __cminpack_func__ ( lmdif1 ) ( __cminpack_decl_fcn_mn__ void *p , int m , int ... | PInvoke lmdif1 signature |
C# | I need to integrate an ASP.NET MVC website with a 3rd party COM application . The code looks something like this : The problem is that after a while I start getting COMExceptions most probably because I never close that context using obj.ReleaseApplicationContext ( ) . So I 'm thinking about writing a wrapper implement... | Type type = Type.GetTypeFromProgID ( progID ) ; dynamic obj = Activator.CreateInstance ( type ) ; if ( ! obj.DBOpenedStatus ) { obj.InitApplicationContext ( ) ; //do stuff with other COM objects } lock ( _locker ) { using ( MyComContextWrapper comContext = new MyComContextWrapper ( ) ) { //do stuff with other COM objec... | COM and thread safety |
C# | I have been working on a Windows 8.1 RT app where the user loads an image with Stretch=Uniform . The image can be as small as possible and as big as possible.The clipping happens in my user control and my user control appears when I tap/press and hold on the screen/image.Clipping happens when when I tap and hold and mo... | < Page x : Class= '' App78.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : App78 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxml... | Clipping a low resolution image using Transforms and assigning it to my user control |
C# | In python I have the following : this is a structure to represent a graph and that I find nice because its structure is the same as the one of one of it 's nodes so I can use it directly to initiate a search ( as in depth-first ) . The printed version of it is : And it can be used like : Now , I 'm curious to know how ... | graph = { } graph [ 1 ] = { } graph [ 2 ] = { } graph [ 3 ] = { } graph [ 1 ] [ 3 ] = graph [ 3 ] graph [ 2 ] [ 1 ] = graph [ 1 ] graph [ 2 ] [ 3 ] = graph [ 3 ] graph [ 3 ] [ 2 ] = graph [ 2 ] { 1 : { 3 : { 2 : { 1 : { ... } , 3 : { ... } } } } , 2 : { 1 : { 3 : { 2 : { ... } } } , 3 : { 2 : { ... } } } , 3 : { 2 : { ... | Creating in c # , c++ and java a strong typed version of a python weak typed structure |
C# | I have a Xamarin.Forms app that implements certificate pinning utilizing the ServicePointManager.ServerCertificateValidationCallback class and method . On Android and iOS , this works without issue in that it will allow connections to expected services whose certificate keys have been pinned and disallow connections fo... | ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate ; private static bool ValidateServerCertficate ( object sender , X509Certificate certificate , X509Chain chain , SslPolicyErrors sslPolicyErrors ) { return false ; } | UWP ServicePointManager.ServerCertificateValidationCallback |
C# | Is there any way of being notified when something subscribes to an event in my class , or do I need to wrap subscription/unsubsription in methods eg : instead ofThe reason I ask is because the event is already exposed directly on a ISomeInterface but this particular implementation needs to know when stuff subscribes/un... | public class MyClass : ISomeInterface { public event SomeEventHandler SomeEvent ; //How do I know when something subscribes ? private void OnSomeEventSubscription ( SomeEventHandler handler ) { //do some work } private void OnSomeEventUnsubscription ( SomeEventHandler handler ) { //do some work } } public class MyClass... | Any way to be notified when something subscribes to an event / delegate ? |
C# | The following code compiles : because defau1t is interpreted as a goto label . However in the following case : the compiler correctly identifies the mistake : error CS1525 : Unexpected symbol defau1t ' , expecting } ' , case ' , ordefault : 'Why is that ? What 's the reason of allowing arbitrary labels inside the switc... | int a = 0 ; switch ( a ) { case 1 : return ; defau1t : // note the typo return ; } switch ( a ) { defau1t : return ; } | What 's the reason of allowing arbitrary labels inside the switch statements ? |
C# | I want to create a generic class where the type of the class can Parse strings.I want to use this class for any class that has a static function Parse ( string ) , like System.Int32 , System.Double , but also for classes like System.Guid . They all have a static Parse functionSo my class needs a where clause that const... | class MyGenericClass < T > : where T : ? ? ? what to do ? ? ? { private List < T > addedItems = new List < T > ( ) public void Add ( T item ) { this.AddedItems.Add ( item ) ; } public void Add ( string itemAsTxt ) { T item = T.Parse ( itemAsTxt ) ; this.Add ( item ) ; } } | Generic class where type can Parse strings |
C# | I 'm trying to find a good way to cumulatively apply up to 5 Func 's to the same IEnumerable . Here is what I came up with : I thought that it would apply these in a cumulative fashion , however , I can see from the results that it 's actually just applying the last one ( DepartmentFilter ) .There are 2^4 possible comb... | private Func < SurveyUserView , bool > _getFilterLambda ( IDictionary < string , string > filters ) { Func < SurveyUserView , bool > invokeList = delegate ( SurveyUserView surveyUserView ) { return surveyUserView.deleted ! = `` deleted '' ; } ; if ( filters.ContainsKey ( `` RegionFilter '' ) ) { invokeList += delegate ... | Need to & & together an indeterminate number of Func < TEntity , bool > |
C# | My task is simple : I have a CSV file inside a C # string , split with semicolons . I need to add spaces for each empty cell . A ; B ; ; ; ; C ; should become A ; B ; ; ; ; C ; . Right now , I 'm using the replace method twice : That 's necessary , because in the first pass , it will replace any occurance of ; ; with a... | csv = csv.Replace ( `` ; ; '' , `` ; ; '' ) .Replace ( `` ; ; '' , `` ; ; '' ) ; | Better way to add spaces between double semicolons |
C# | There is a confusion in the arrangement of codes and the place where it pleases so I hope to find an explanation for the following : When I have a server `` https : //localhost:48009/ '' and the application is equipped with all the requirements of Signal-R and also Hub exists on it.in folder Hubs There is a Hub Class C... | using System ; using System.Web ; using Microsoft.AspNet.SignalR ; namespace SignalRChat { public class ChatHub : Hub { public void Send ( string name , string message ) { // Call the addNewMessageToPage method to update clients . Clients.All.addNewMessageToPage ( name , message ) ; } } } @ { ViewBag.Title = `` Chat ''... | How to bring Hub content from Any server to *another server* project Hub ? |
C# | I 'm working through some computer science exercises and I 'm embarrassed to say I do n't know how to console print the above stated code in VS Studio . I 've tried over a number of days , and part of my problem is that I do n't actually know the name of the above mentioned construction ( figuratively speaking ) . I 'v... | public static class PythagoreanTriplet { public static IEnumerable < ( int a , int b , int c ) > TripletsWithSum ( int sum ) { return Enumerable.Range ( 1 , sum - 1 ) .SelectMany ( a = > Enumerable.Range ( a + 1 , sum - a - 1 ) .Select ( b = > ( a : a , b : b , c : sum - a - b ) ) ) .Where ( x = > x.a * x.a + x.b * x.b... | How to Console.Writeline IEnumerable < ( int a , int b , int c ) > ? |
C# | Is any difference between : And ? What are the benefits of use the first one method ? | public void Method1 < T > ( class1 c , T obj ) where T : Imyinterface public void Method2 ( class1 c , Imyinterface obj ) | interface as argument or generic method with where - what is the difference ? |
C# | I am learning the reflections concepts in c # . I have a class like this In another class I would like to extract the values from the list . I have stupid ways to do it likeThe operations in the foreach loops are similar . How can I do this in a clear way by using reflections ? | public class pdfClass { public List < AttributeProperties > TopA { get ; set ; } public List < AttributeProperties > TopB { get ; set ; } public List < AttributeProperties > TopC { get ; set ; } } public void ExtractValue ( pdfClass incomingpdfClass , string type ) { switch ( type ) { case `` TopA '' : foreach ( var li... | Simple question : Reflections in C # |
C# | style that I have to create in code-behind . It has a checkbox that looks like this..How I do in code-behind ? | < GridView > < GridViewColumn Width= '' 30 '' > < GridViewColumn.CellTemplate > < DataTemplate > < StackPanel > < CheckBox/ > < /StackPanel > < /DataTemplate > < /GridViewColumn.CellTemplate > < /GridViewColumn > -- > < GridViewColumn Header= '' Groups '' DisplayMemberBinding= '' { Binding Groups } '' / > < GridViewCol... | WPF How to set checkbox in Gridview binding in code behind |
C# | I have a consumer class responsible for consuming a string and deciding what to do with it . It can either parse and insert the parse data in a database or notify an administrator . Below is my implementation.Below is my unit test.Is it code smell to mix mocks and real implementation in unit tests ? Also , how do alway... | public void Consume ( string email ) { if ( _emailValidator.IsLocate ( email ) ) { var parsedLocate = _parser.Parse ( email ) ; // Insert locate in database } else if ( _emailValidator.IsGoodNightCall ( email ) ) { // Notify email notifying them that a locate email requires attention . _notifier.Notify ( ) ; } } // Arr... | Is it a test smell to mix in real implementation and mocks ? |
C# | After some resent tests I have found my implementation can not handle very much recursion . Although after I ran a few tests in Firefox I found that this may be more common than I originally thought . I believe the basic problem is that my implementation requires 3 calls to make a function call . The first call is made... | public static object Call ( ExecutionContext context , object value , object [ ] args ) { var func = Reference.GetValue ( value ) as ICallable ; if ( func == null ) { throw new TypeException ( ) ; } if ( args ! = null & & args.Length > 0 ) { for ( int i = 0 ; i < args.Length ; i++ ) { args [ i ] = Reference.GetValue ( ... | How can I improve the recursion capabilities of my ECMAScript implementation ? |
C# | For ExampleTo something like | txtUnitTotalQty.Text = `` '' ; txtPrice.Text = `` '' ; txtUnitPrice.Text = `` '' ; lblTotalvalue.Text = `` '' ; ( txtUnitTotalQty , txtPrice , txtUnitPrice , lblTotalvalue ) .Text = `` '' ; | Can I run multiple control but same method in C # |
C# | I tried the following code : This code work fine and result will contain -2 ( I know why ) .But when doing this : This will not compile because of overflow problem.Why ? | int x , y ; x = y = int.MaxValue ; int result = x + y ; const int x = int.MaxValue ; const int y = int.MaxValue ; int result = x + y ; | Overflow error when doing arithmetic operations with constants |
C# | I have a class , which holds some details in a large data structure , accepts an algorithm to perform some calculations on it , has methods to validate inputs to the data structure . But then I would like to return the data structure , so that it can be transformed into various output forms ( string / C # DataTable / c... | class MyProductsCollection { private IDictionary < string , IDictionary < int , ISet < Period > > > products ; // ctors , verify input , add and run_algorithm methods } interface IProductsCollection { IDictionary < string , IDictionary < int , ISet < IPeriod > > > GetData ( ) ; // other methods } | OO Design - Exposing implementation details through an interface |
C# | Whats the difference between these three ways of creating a new List < string > in C # ? | A = new List < string > ( ) ; B = new List < string > { } ; C = new List < string > ( ) { } ; | Whats the difference between these three ways of creating a new List < string > in C # ? |
C# | Okay - I 'm not even sure that the term is right - and I 'm sure there is bound to be a term for this - but I 'll do my best to explain . This is not quite a cross product here , and the order of the results are absolutely crucial.Given : Where each inner enumerable represents an instruction to produce a set of concate... | IEnumerable < IEnumerable < string > > sets = new [ ] { /* a */ new [ ] { `` a '' , `` b '' , `` c '' } , /* b */ new [ ] { `` 1 '' , `` 2 '' , `` 3 '' } , /* c */ new [ ] { `` x '' , `` y '' , `` z '' } } ; set a* = new string [ ] { `` abc '' , `` ab '' , `` a '' } ; set b* = new string [ ] { `` 123 '' , `` 12 '' , ``... | Calculate a set of concatenated sets of n sets |
C# | Is there a way to lock or freeze a part of code against formatting in Visual Studio ? I want to protect the following code : to be formatted as : but still be able to format the rest of the document . | Method ( `` This is a long text '' , 12 , true ) ; Method ( `` Hi '' , 558 , true ) ; Method ( `` Short text '' , 1 , false ) ; Method ( `` This is a long text '' , 12 , true ) ; Method ( `` Hi '' , 558 , true ) ; Method ( `` Short text '' , 1 , false ) ; | Freeze part of code against formatting |
C# | So I am recently writing a relatively complex application written in C # that performs an array of small tasks repeatedly . When I first started the application I realized that a lot of the code I was typing was repetitive and so I began encapsulating the majority of the app 's logic into separate helper classes that I... | try { ItemManager.SaveTextPost ( myPostItem ) ; } // Majority of the time there is more than one catch ! catch { //^^^Not to mention that I have to handle multiple types of exceptions //in order to log them correctly ( more catches..ugh ! ) MessageBox.Show ( `` There was an error saving the post . `` ) ; //Perform logg... | Where is the correct the place to handle exceptions in my C # applications ? |
C# | The instructions : Please write a piece of code that takes as an input a list in which each element is another list containing an unknown type and which returns a list of all possible lists that can be obtained by taking one element from each of the input lists . For example : [ [ 1 , 2 ] , [ 3 , 4 ] ] , should return ... | public static void Main ( string [ ] args ) { //Create a list of lists of objects . var collections = new List < List < object > > ( ) ; collections.Add ( new List < object > { 1 , 5 , 3 } ) ; collections.Add ( new List < object > { 7 , 9 } ) ; collections.Add ( new List < object > { `` a '' , `` b '' } ) ; //Get all t... | Generate permutations using polymorphic method |
C# | I mostly develop using C # , but I think this question might be suitable for other languages as well.Also , it seems like there is a lot of code here but the question is very simple.Inlining , as I understand it , is the compiler ( in the case of C # the Virtual Machine ) replacing a method call by inserting the body o... | static Main ( ) { int number = 7 ; bool a ; a = IsEven ( number ) ; Console.WriteLine ( a ) ; } bool IsEven ( int n ) { if ( n % 2 == 0 ) // Two conditional return paths return true ; else return false ; } static Main ( ) { int number = 7 ; bool a ; if ( number % 2 == 0 ) a = true ; else a = false ; Console.WriteLine (... | How does a method with an absolute return path gets inlined ? |
C# | If I create an extension method on Enum called HasFlag , whenever I try to call HasFlag on an enum instance , it uses the extension method , rather than the instance method . Why ? With code : Compiles to : Why does n't the compiler use the Enum.HasFlag instance method ? | public static class Extensions { public static bool HasFlag ( this Enum e ) { return false } } public enum Foo { A , B , C } public void Whatever ( ) { Foo e = Foo.A ; if ( e.HasFlag ( ) ) { // ... } } public void Whatever ( ) { Foo e = Foo.A ; if ( Extensions.HasFlag ( e ) ) { // ... } } | Why does HasFlag extension method on Enum trump Enum.HasFlag ? |
C# | I 'm looking for something similar to what would have a signature like this : This needs to avoid potential race conditions across threads , processes , and even other machines accessing the same filesystem , without requiring the current user to have any more permissions than they would need for File.Create . Currentl... | static bool TryCreateFile ( string path ) ; static bool TryCreateFile ( string path ) { try { // If we were able to successfully create the file , // return true and close it . using ( File.Open ( path , FileMode.CreateNew ) ) { return true ; } } catch ( IOException ) { // We want to rethrow the exception if the File.O... | How do I try to create a file , and return a value indicating whether it was created or not ? |
C# | I am confused about what I need to do in order to correctly `` set up '' my unverifiable method so that it conforms to code access security guidelines.Given the following methodwhich is deemed unverifiable by PEVerify , what attributes do I absolutely need to apply to the method definition ? [ SecurityCritical ] ? [ Se... | [ MethodImpl ( MethodImplOptions.ForwardRef ) ] private extern void DoStuffUnverifiable ( ) ; | Confusion regarding code access security with unverifiable code |
C# | I want to test if an xml attribute is present . Given this : This first test works : '' GetNamedItem '' is supposed to return null , but the following test throws an exception complaining about the null it returns.Why the difference ? Just curious . | XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes ; if ( null ! = PG_attrColl [ `` SomeAttribute '' ] ) if ( null ! = PG_attrColl.GetNamedItem ( `` SomeAttribute '' ) .Value ; ) | Why can one null return be tested but another throws an exception ? |
C# | There 's a lot of code like this in company 's application I 'm working at : From my understanding of Lazy this is totally meaningless , but I 'm new at the company and I do n't want to argue without reason.So - does this code have any sense ? | var something = new Lazy < ISomething > ( ( ) = > ( ISomething ) SomethingFactory .GetSomething < ISomething > ( args ) ) ; ISomething sth = something.Value ; | C # Using Lazy.Value right after its declaration |
C# | I have a use case in Q # where I have qubit register qs and need to apply the CNOT gate on every qubit except the first one , using the first one as control . Using a for loop I can do it as follows : Now , I wanted to give it a more functional flavor and tried instead to do something like : The Q # compiler does not a... | for ( i in 1..Length ( qs ) -1 ) { CNOT ( qs [ 0 ] , qs [ i ] ) ; } ApplyToEach ( q = > CNOT ( qs [ 0 ] , q ) , qs [ 1..Length ( qs ) -1 ] ) ; | Can I use lambda in Q # to operate on qubits ? |
C# | The .Net Equals ( ) returns different results , though we are comparing the same values . Can someone explain me why that is the case ? Has it got to do anything with the range of the types we are comparing against ? | class Program { static void Main ( string [ ] args ) { Int16 a = 1 ; Int32 b = 1 ; var test1 = b.Equals ( a ) ; //true var test2 = a.Equals ( b ) ; //false } } | Why does Int32.Equals ( Int16 ) return true where the reverse does n't ? |
C# | I had an interesting interview question the other day , which I really struggled with . The ( highly ambitious ) spec required me to write , in C # , parsers for two different data streams . Here is a made-up example of the first stream : where 30 is the currency pair , 35 is the number of tenors , and 50,51,52 are the... | 30=EUR/USD,35=3,50=ON,51=12.5,52=13.5,50=6M,51=15.4,52=16.2,50=1Y,51=17.2,52=18.3 List < DataElement > Parse ( string row ) { string currency=string.Empty ; DataElement [ ] elements = null ; int j = 0 ; bool start = false ; string [ ] tokens = row.Split ( ' , ' ) ; for ( int i = 0 ; i < tokens.Length ; i++ ) { string [... | Processing a data feed format |
C# | I 've got a list of 369 different names and I want to print these names into a csv file . All 's going well until I take a look at the outputted csv file and it only has 251 rows . I 've tried outputting to a .txt instead , and still it only outputs 251 rows . Ive stepped through with the debugger and it is still calli... | List < String > names = new List < String > ( ) ; //Retrieve names from a separate source.var writer = new StreamWriter ( File.OpenWrite ( @ '' C : names.txt '' ) ) ; for ( int i = 0 ; i < names.Count ; i++ ) { System.Console.WriteLine ( names [ i ] .ToString ( ) ) ; writer.WriteLine ( names [ i ] .ToString ( ) ) ; } S... | Why does my C # program only write 251 rows to a file ? |
C# | I am trying to add collection initializing to my class . I read about the initializers here : https : //msdn.microsoft.com/en-us/library/bb384062.aspx # Anchor_2I 'll quote the important part that puzzles me : Collection initializers let you specify one or more element initializers when you initialize a collection clas... | public class PropertySpecificationCollection { private List < PropertySpecification > _internalArr ; public void Add ( PropertySpecification item ) { _internalArr.Add ( item ) ; } } | Using collection initializer on my own class |
C# | Why is it necessary in .NET Web API to have a a method that reads the content of an HTTP response asynchronously , given that there is already a method to make the request asynchronously ? Said another way , if I am using HttpClient.GetAsync ( or PostAsync , or PutAsync , etc ) , is the code really any more asynchronou... | using ( var client = new HttpClient ( ) ) { var response = await client.GetAsync ( `` ... '' ) ; response.EnsureSuccessStatusCode ( ) ; return await response.Content.ReadAsAsync < Foo > ( ) ; } using ( var client = new HttpClient ( ) ) { var response = await client.GetAsync ( `` ... '' ) ; response.EnsureSuccessStatusC... | Why await both the asynchronous request and the reading of its contents ? |
C# | I recently had a program fail in a production server because the server was missing a time zone , so the following line threw an exception : I fixed it exporting the time zone registry branch from a test server , importing it to the production server.My question is , is it possible to install time zones selectively ? H... | TimeZoneInfo.ConvertTime ( date , TimeZoneInfo.Local , TimeZoneInfo.FindSystemTimeZoneById ( `` Argentina Standard Time '' ) ) | Is it possible to install time zones on a server ? |
C# | I 've been refactoring a common pattern in my project and found it 's not as simple as using a LINQ Select to an async function.For context , here is how it is done currently.Now if I try to replace the ForEach loop section using LINQ : It complains Type arguments can not be inferred by the usage which leads me to beli... | async Task < ICollection < Group > > ExecuteQueryGroupsForDomain ( DomainInfo domain , int batchSize , CancellationToken ct ) { try { return await BlahBlahActuallyGoGetGroupsForDomainHere ( domain , batchSize , ct ) ; } catch ( Exception e ) { return null ; } } var executeQueries = new List < Func < CancellationToken ,... | Better way to Select to an async Func ? |
C# | Let 's say I have : And containers of these two types of animals : Is there a way to cast 'lions ' and 'boars ' so that I can pass them into a function like this ? | public class Animal { virtual public void Attack ( ) { } ; } public class Lion : Animal { public override void Attack ( ) { base.Attack ( ) ; } } public class Boar : Animal { public override void Attack ( ) { base.Attack ( ) ; } } Dictionary < int , Lion > lions ; Dictionary < int , Boar > boars ; void IterateTable ( D... | How do you cast a dictionary < int , child > to dictionary < int , parent > ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.