lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | It is recommended e.g . here to use ConfigureAwait ( false ) as much as possible on awaited tasks.Does this recommendation also extend to methods that return IAsyncAction , for example StreamSocket.ConnectAsync ( ) ? That is , instead of simply writing this in my class library : I should rather write this ? | await socket.ConnectAsync ( hostName , port ) ; await socket.ConnectAsync ( hostName , port ) .AsTask ( ) .ConfigureAwait ( false ) ; | Should I use ConfigureAwait ( false ) when awaiting IAsyncAction ? |
C# | Currently , not even the simplest examples of using the 'ExpandoObject ' work on my machine.Both ( from this website ) and ( from the MSDN examples ) fail with a RuntimeBinderException . I presume I 've misconfigured something , but I am at a loss about what it might be.I am using .NET v4.0.30319 and Visual Studio 2010... | dynamic obj = new ExpandoObject ( ) ; obj.Value = 10 ; var action = new Action < string > ( ( line ) = > Console.WriteLine ( line ) ) ; obj.WriteNow = action ; obj.WriteNow ( obj.Value.ToString ( ) ) ; dynamic sampleObject = new ExpandoObject ( ) ; sampleObject.test = `` Dynamic Property '' ; Console.WriteLine ( sample... | Why does ExpandoObject not work as expected ? |
C# | I created a simple benchmark out of curiosity , but can not explain the results.As benchmark data , I prepared an array of structs with some random values . The preparation phase is not benchmarked : Basically , I wanted to compare these two clamp implementations : Here are my benchmark methods : I 'm using BenchmarkDo... | struct Val { public float val ; public float min ; public float max ; public float padding ; } const int iterations = 1000 ; Val [ ] values = new Val [ iterations ] ; // fill the array with randoms static class Clamps { public static float ClampSimple ( float val , float min , float max ) { if ( val < min ) return min ... | Why does Mono run a simple method slower whereas RyuJIT runs it significantly faster ? |
C# | Good day SO ! I was trying to add two byte variables and noticed weird result . when i tried to run the program , It displaysWhat happened to the above code ? Why does n't the compiler throws an OverflowException ? How can I possibly catch the exception ? I 'm a VB guy and slowly migrating to C # : ) Sorry for the ques... | byte valueA = 255 ; byte valueB = 1 ; byte valueC = ( byte ) ( valueA + valueB ) ; Console.WriteLine ( `` { 0 } + { 1 } = { 2 } '' , valueA.ToString ( ) , valueB.ToString ( ) , valueC.ToString ( ) ) ; 255 + 1 = 0 | byte + byte = unknown result |
C# | I have what seems to be a simple problem that I am having a hard time modeling in code ( C # ) -I am trying to find the highest potential credit hours available to a person attending a conference . Courses have time blocks , such as Security 101 @ 9AM-10AM , Finance 202 @ 4PM-6PM , etc.The main rule is , you ca n't att... | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| COURSE | START | END || -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -|| FINANCE 101 | 9:00 AM | 10:00 AM || FINANCE 102 | 10:00 AM | 11:00 AM || PYTHON 300 | 10:00 AM | 11:00 AM || SECURITY 101 | 11:00 AM | 1... | How do I get all non-overlapping permutations for a series of time blocks ? |
C# | For the life of me , I ca n't figure out why all the foos are not null.I 'm assuming the .ForAll ( ) should be executing before I call the .All ( ) method , but it 's not ? | public class Foo { public string Bar { get ; set ; } } static void Main ( string [ ] args ) { var foos = new List < Foo > { new Foo ( ) , new Foo ( ) , new Foo ( ) } ; var newFoos = foos .AsParallel ( ) .Select ( x = > { x.Bar = `` '' ; return x ; } ) ; newFoos.ForAll ( x = > x = null ) ; var allFoosAreNull = newFoos.A... | Parallel LINQ - .Select ( ) + .ForAll ( ) returning bizarre results |
C# | Why do we need more than one await statement in a C # method ? E.g . here we have three await statements : In case we will remove the second and the third await statements in the SeedAsync no extra threads will be blocked , since already after the first await we are not blocking any useful threads and we already alloca... | using System ; using System.Threading.Tasks ; using Volo.Abp.Data ; using Volo.Abp.DependencyInjection ; using Volo.Abp.Domain.Repositories ; namespace Acme.BookStore { public class BookStoreDataSeederContributor : IDataSeedContributor , ITransientDependency { private readonly IRepository < Book , Guid > _bookRepositor... | Why do we need more than one ` await ` statement in a C # method ? |
C# | When working with MVVM and Prism i find myself doing a lot of casting , as most parameters are interfacesExorMy question is , whats the cost involved . Are these operations costly memory or cpu wise , should they be avoided.Any views ? | public void AddCrSubSystemsToPlant ( IPlantItem plantItm , CRArticleItem crItm ) { OSiteSubSystem itm = ( OSiteSubSystem ) crItm ; itm.PartData.Order = ( ( OSiteEquipment ) plantItm ) .SubSystems.Count ( ) + 1 ; ( ( OSiteEquipment ) plantItm ) .SubSystems.Add ( itm ) ; } public void DeletePart ( IPlantItem plantItem ) ... | Whats the cost of casting parameters |
C# | In the synchronous world , C # makes the management of all things disposable really rather easy : However , when we go async , we no longer have the convenience of the using block . One of the best strategies I 've encountered is the CCR iterator which allows us to use async code `` as if it were synchronous '' . This ... | using ( IDisposable someDisposable=bla.bla ( ) ) { //do our bidding } //do n't worry too much about it | Failsafe disposal in an async world |
C# | Why does the Equals method return a different result from within the generic method ? I think that there 's some automatic boxing here that I do n't understand.Here 's an example that reproduces the behavior with .net 3.5 or 4.0 : Output : Edit : This code works as desired without many compromises : Followup : I filed ... | static void Main ( string [ ] args ) { TimeZoneInfo tzOne = TimeZoneInfo.Local ; TimeZoneInfo tzTwo = TimeZoneInfo.FindSystemTimeZoneById ( tzOne.StandardName ) ; Console.WriteLine ( Compare ( tzOne , tzTwo ) ) ; Console.WriteLine ( tzOne.Equals ( tzTwo ) ) ; } private static Boolean Compare < T > ( T x , T y ) { if ( ... | Unexpected behavior in c # generic method on .Equals |
C# | Is there a linq command that will filter out duplicates that appear in a sequence ? Example with ' 4 ' : Thanks . | Original { 1 2 3 4 4 4 5 6 7 4 4 4 8 9 4 4 4 } Filtered { 1 2 3 4 5 6 7 4 8 9 4 } | Linq query that reduces a subset of duplicates to a single value within a larger set ? |
C# | While experimenting with closures in C # I found out that they work rather unexpectedly if they capture an iterator variable in a loop.The above code produces a strange result ( I 'm using .NET 4.5 compiler ) : Why is the value of i captured differently for 2 almost identical loops ? | var actions = new List < Action > ( ) ; foreach ( int i in new [ ] { 1 , 2 } ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; for ( int i = 3 ; i < = 4 ; i++ ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; foreach ( var action in actions ) action ( ) ; 1255 | Closures behaving differently in for and foreach loops |
C# | example : this causes a cyclic struct layout , but i do n't see the cycle . if Id had a field of type T , sizeof would be undefined , but it doesn't.is this a mono bug , or part of the spec ? | struct Id < T > { int id ; } struct Thing { public Id < Thing > id ; } | why do i get a `` cycle in the struct layout '' with phantom types in c # ? |
C# | `` test1 '' seems to be an IEnumerable with v1 and v2 ( params ) as fields and `` Test1 '' is NOT called . `` Test2 '' works a `` designed '' : ) whats going on ? | using System ; using System.Collections.Generic ; using System.Text ; using System.Collections ; namespace ConsoleApplication4 { class Program { static void Main ( string [ ] args ) { var test1 = Test1 ( 1 , 2 ) ; var test2 = Test2 ( 3 , 4 ) ; } static IEnumerable Test1 ( int v1 , int v2 ) { yield break ; } static IEnu... | yield break ; - crazy behaviour |
C# | The question is about C # language specification and CIL language specification , as well as Microsoft 's and Mono 's C # compiler behavior . I 'm building some code analysis tools ( no matter what ) , which operate on CIL . Considering a few code samples , I notice that code statements ( try/catch , ifelse , ifthen , ... | IL_0000 : IL_0001 : IL_0002 : // holeIL_001a : IL_001b : | Can a C # statement generate non connected MSIL |
C# | I got into an argument with a co-worker about the use of LINQ to Objects ( IEnumerable , not IQueryable ) in our C # code . I was using LINQ , and he said that we should n't be using an external vendor 's ( Microsoft ) code in our code , but that we should wrap it ourselves in our own layer of abstraction.Now I underst... | from e in employeesselect new { e.Name , e.Id } ; | Should I not use LINQ to objects because Microsoft might change it ? |
C# | I 'm converting some VB6 logic to C # and have encountered the following SELECT/CASE statement.The best conversion I can think of is a series of if/then/else statements which map each range , e.g.Or is there a better way , e.g . some way to put these range values in a hash/array/collection of some sort ? | Select Case ZipCodeCase 1067 To 19417 , 35075 To 35085 , 48455 To 48465 , 55583 To 55596 , 67480 To 67551 , 75392 , 85126 , _ 93047 To 93059 , 21217 To 21739 , 35091 To 35096 , 48480 , 55606 To 55779 , 67655 To 67707 , 76726 To 76835 , _ 85221 To 87679 , 94315 To 94419 , 22844 To 25799 , 35102 , 48488 , 56154 To 56254 ... | How to best convert VB6 `` Select Case 1067 To 2938 ... '' to C # ? |
C# | An ex-coworker wrote this : I read articles like theseCode Project - Custom String Formatting in .NETMSDN - Custom Numeric Format StringsBut I do n't still get it how that format works . Obviously I can see the output but I do n't understand this part { 0 : # ; ; } and the second one . I want to do the same thing for s... | String.Format ( `` { 0 : # ; ; } { 1 : records ; no records ; record } '' , rows , rows - 1 ) ; //Rows is a integer value | Explaining confusing conditional string format |
C# | I need to make a class that wraps two dictionaries together , so that their values can be retrieved by a key of either an int or a string.Properties seem to be the best approach here , but is there a difference between these two implementations ? AndIn either case , the dictionary object is immutable and the elements c... | public class Atlas < TValue > { private Dictionary < int , TValue > _byIndex ; private Dictionary < string , TValue > _byName ; public Dictionary < int , TValue > ByIndex { get { return _byIndex ; } } public Dictionary < string , TValue > ByName { get { return _byName ; } } } public class Atlas < TValue > { public Dict... | Is there a difference between having a private setter OR only defining a getter ? |
C# | So , i 'm new to unit testing , and even more so to test first development . Is it valid for me to have just a single assert.isTrue statement in my unit test where I pass in my method and a valid parameter , and compare it to the known good answer ? MethodTest | public static string RemoveDash ( string myNumber ) { string cleanNumber = myNumber.Replace ( `` - '' , '' '' ) ; return cleanNumber ; } [ TestMethod ( ) ] public void TestRemoveDash ( ) { Assert.IsTrue ( RemoveDash ( `` 50-00-0 '' ) == '' 50000 '' ) ; } | Is it valid to have unit tests with only an assert statement ? |
C# | In C # is there any real difference ( other than syntax ) under the hood between : and ? | myButton.Click += new EventHandler ( myMemberMethod ) ; myButton.Click += myMemberMethod ; | Is there an actual difference in the 2 different ways of attaching event handlers in C # ? |
C# | I have a particular problem that I need help with . I am working with complex proteomics data and one of our plots involves a heatmap of the raw data . These heatmaps I calculate as a raw image that I then resize to fit my chart canvas . The image files that are produced that way are usually very in-balanced when it co... | public static Image Resize ( Image img , int width , int height ) { Bitmap bmp = new Bitmap ( width , height ) ; Graphics graphic = Graphics.FromImage ( ( Image ) bmp ) ; graphic.InterpolationMode = InterpolationMode.NearestNeighbor ; graphic.PixelOffsetMode = PixelOffsetMode.Half ; graphic.DrawImage ( img , 0 , 0 , wi... | Large , odd ratio image resize in C # |
C# | I am developing a HTML form designer that needs to generate static HTML and show this to the user . I keep writing ugly code like this : Is n't there a set of strongly typed classes that describe html elements and allow me to write code like this instead : I just ca n't think of the correct namespace to look for this o... | public string GetCheckboxHtml ( ) { return ( `` & lt ; input type= '' checkbox '' name= '' somename '' / & gt ; '' ) ; } var checkbox = new HtmlCheckbox ( attributes ) ; return checkbox.Html ( ) ; | In C # 3.0 , are there any classes that help me generate static html ? |
C# | I 'm building a report dashboard using C # and JQuery Datatables . One of the reports on the page contains an update panel with a drop down list . When the user changes the selection , the data refreshes based on the ddl selection . Within each block there is also a link that makes a server side call to export the data... | < div id= '' dTopProducts '' class= '' dashboardDiv '' style= '' height:400px ; width:485px ; margin-top : 15px ; margin-bottom:15px ; margin-right : 15px ; '' runat= '' server '' > < asp : UpdatePanel ID= '' upProducts '' runat= '' server '' > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' ddlProductsSector '... | jQuery Datatables ASP.NET issue |
C# | On my page I have : a 'filter ' section - a couple of checkboxes and textboxes , a 'search ' button , grid with paging where the results are displayed . The grid is from Telerik ( http : //demos.telerik.com/aspnet-mvc/grid/index1 ) , but I do n't think this matters.Searching works OK - I can input some text or check a ... | public ActionResult Index ( ) { // On page load display all data without filters . var filter = new OverviewFilterModel { Type1 = true , Type2 = true , WorkingOrder = `` '' } ; ViewBag.Results = GetResults ( filter ) ; return View ( new HomeModel { Filter = filter } ) ; } public ActionResult Search ( HomeModel model ) ... | Model is null after postback in pager |
C# | What is the [ and ] in c # ? what is it used for ? what does it mean ? example | [ DefaultValue ( null ) ] [ JsonName ( `` name '' ) ] public string Name { get { if ( this.name == null ) { return String.Empty ; } return this.name ; } } | What is [ and ] in c # ? |
C# | I am reading the MCTS Self-Paced Training Kit ( Exam 70-536 ) : Microsoft .NET Framework—Application Development Foundation , Second Edition eBook.Now I am finishing off the threading chapter ( nr . 7 ) . In the questions at the end of lesson 2 , the is one question ( nr . 2 ) that asks : `` You are writing a method th... | lock ( file ) { // Read } ReaderWriterLock rwl = new ReaderWriterLock ( ) ; rwl.AcquireReaderLock ( 10000 ) ; // Readrwl.ReleaseReaderLock ( ) ; | Is this an error in the MCTS Self-Paced Training Kit ( Exam 70-536 ) ? |
C# | Using this construct : I get an error saying CS0165 use of unassigned local variable 'value ' which is not what I expect . How could value possibly be undefined ? If the dictionary is null the inner statement will return false which will make the outer statement evaluate to false , returning Default.What am I missing h... | var dict = new Dictionary < int , string > ( ) ; var result = ( dict ? .TryGetValue ( 1 , out var value ) ? ? false ) ? value : `` Default '' ; | Null-coalescing out parameter gives unexpected warning |
C# | I have the following generic classes : Somewhere in my code , I would like to test whether a given generic inherits from Base < T > , without creating a particular instance of the generic . How do I do that ? EDIT : Thank you Mark . Now I see the light . I originally tried the following : Apparently , this is correct .... | class Base < T > where T : ... { ... } class Derived < T > : Base < T > where T : ... { ... } class Another < T > where T : ... { ... } class DerivedFromDerived < T > : Derived < T > where T : ... { ... } static bool DerivedFromBase ( Type type ) { /* ? ? ? */ } static void Main ( string [ ] args ) { Console.WriteLine ... | How to test whether two generics have a base-subclass relationship without instantiating them ? |
C# | first , it 's not a duplication of What does the @ symbol before a variable name mean in C # ? as group is not a preserved keyword.I wrote some code and the resharper suggested me to add @ before the variable group.Any idea why ? | var group = GetDefaultGroup ( ClientServiceCommon.Poco.Group ) ; filteredPairs = @ group.Pairs.ToList ( ) ; | what does @ before variabe means in c # ? |
C# | I 'm trying to build the C # wrappers for RDKit , but have been struggling to make progress . I 've attempted two routes : n.b . This question is long and unhelpful . Long story short use NuGet ( see answer below ) .Attempt OneDocs from RDKit /Code/JavaWrappers/csharp_wrapperThe first one is found in https : //github.c... | cmake_minimum_required ( VERSION 3.14 ) project ( GraphMolCSharp ) set ( SWIG_FOUND TRUE ) # This has been addedset ( SWIG_DIR $ { CMAKE_CURRENT_SOURCE_DIR } ) # This has been addedset ( SWIG_EXECUTABLE swig.exe ) # This has been addedset ( SWIG_VERSION 4.0 ) # This has been addedfind_package ( SWIG ) # This has been a... | Trying to build the C # wrappers for RDKit with build.bat from bp-kelley/rdkit-csharp |
C# | Suppose I want to check a bunch of objects to make sure none is null : It is an alluring prospect to write a helper function to accept a variable number of arguments and simplify this kind of check : Then the above code could become : Right ? Wrong . If obj is null , then I 'll get a NullReferenceException when I try t... | if ( obj ! = null & & obj.Parameters ! = null & & obj.Parameters.UserSettings ! = null ) { // do something with obj.Parameters.UserSettings } static bool NoNulls ( params object [ ] objects ) { for ( int i = 0 ; i < objects.Length ; i++ ) if ( objects [ i ] == null ) return false ; return true ; } if ( NoNulls ( obj , ... | Can I force my own short-circuiting in a method call ? |
C# | I 'm trying to compile a .cs file using a CSharpCodeProvider from a .net 3.5 app and I want to target the .net4 compiler but I 'm getting this error `` Compiler executable file csc.exe can not be found '' . I have .net4 installed . Below is the code that I 'm using with some lines omitted for brevity . When I set Compi... | CompilerResults results = null ; using ( CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < string , string > ( ) { { `` CompilerVersion '' , `` v4.0 '' } , } ) ) { CompilerParameters options = new CompilerParameters ( ) ; ... results = provider.CompileAssemblyFromFile ( options , Directory.GetFile... | Is it possible to target the .net4 compiler from a .net3.5 app with a CSharpCodeProvider ? |
C# | In C # I am trying to write code where I would be creating a Func delegate which is in itself generic . For example the following ( non-Generic ) delegate is returning an arbitrary string : I on the other hand want to create a generic which acts similarly to generic methods . For example if I want a generic Func to ret... | Func < string > getString = ( ) = > `` Hello ! `` ; Func < T > < T > getDefaultObject = < T > ( ) = > default ( T ) ; | C # Generic Generics ( A Serious Question ) |
C# | Possible Duplicate : Why check this ! = null ? The part I do n't understand is the fact that it is checking for the current instance , this , against null . The comment is a bit confusing , so I was wondering what does that comment actually mean ? Can anyone give an example of how this could break if that check was not... | // Determines whether two strings match . [ ReliabilityContract ( Consistency.WillNotCorruptState , Cer.MayFail ) ] public override bool Equals ( Object obj ) { //this is necessary to guard against reverse-pinvokes and //other callers who do not use the callvirt instruction if ( this == null ) throw new NullReferenceEx... | Why does String.Equals ( Object obj ) check to see if this == null ? |
C# | Is it possible to build up a bit mask based on the result of a linq query ; for example : | class MyClass { public int Flag { get ; set ; } public bool IsSelected { get ; set ; } } myVar = GetlistMyClass ( ) ; int myFlag = myVar.Where ( a = > a.IsSelected ) .Select ( ? ) ; | Building a bit flag using linq / lambda |
C# | I 've created a azure mobile service which basically consist of 2 Entities and 2 TableControllers . Those both entities have a 1:1 relation . The controllers are the standard scaffold generated controllers . When I 'm try to insert a entity1 instance with a reference to a already existing entity2 i get the following me... | public class Entity1 : EntityData { public int Value { get ; set ; } public DateTime Date { get ; set ; } public string Name { get ; set ; } public virtual Entity2 Reference { get ; set ; } } public class Entity2 : EntityData { public string Name { get ; set ; } } { `` $ id '' : '' 1 '' , '' message '' : '' The operati... | Creating an entity with a reference to an other entity in azure mobile service |
C# | Why C # compiler allows this to compile and throws runtime exception when run ? This does compile with any interface and it does n't compile if you replace IDisposable with concrete class . | class Program { static void Main ( string [ ] args ) { IEnumerable < Test > list = new List < Test > ( ) { new Test ( ) } ; foreach ( IDisposable item in list ) { } } } public class Test { } | C # foreach unexpected behavior |
C# | Say I 'm trying to test a simple Set classAnd suppose I 'm trying to test that no duplicate values can exist in the set . My first option is to insert some sample data into the set , and test for duplicates using my knowledge of the data I used , for example : My second option is to test for my condition generically : ... | public IntSet : IEnumerable < int > { Add ( int i ) { ... } //IEnumerable implementation ... } //OPTION 1 void InsertDuplicateValues_OnlyOneInstancePerValueShouldBeInTheSet ( ) { var set = new IntSet ( ) ; //3 will be added 3 times var values = new List < int > { 1 , 2 , 3 , 3 , 3 , 4 , 5 } ; foreach ( int i in values ... | Unit Testing - Algorithm or Sample based ? |
C# | Why the designers of C # did not allow for something like this ? One of the most important ways to safe multi-threading is the use of immutable objects/classes , yet there is no way to declare a class as immutable . I know I can make it immutable by proper implementation but having this enforced by class declaration wo... | public readonly class ImmutableThing { ... } | Why there is no declarative immutability in C # ? |
C# | I need some help trying to figure what I 'm doing wrong . I 'm trying to get a collection of items from the system log on a separate thread to keep the form from being frozen during the collection process . I can get the background worker to grab them all , but I am having some issues add them to the ListBox on the for... | private void backgroundWorker1_DoWork ( object sender , DoWorkEventArgs e ) { foreach ( System.Diagnostics.EventLogEntry entry in eventLog1.Entries ) { listBox1.Items.Add ( entry.EntryType.ToString ( ) + `` - `` + entry.TimeWritten + `` - `` + entry.Source ) ; } } | Working with threads C # |
C# | So I have a basic crypto class . Note that this is a simplified implementation to illustrate the question.Now to my mind both these methods have an extra byte array and string instance . xmlString and bytes in Encrypt and decryptedString and decryptedBytes in DecryptSo how can I rework the usage of streams in this clas... | class Crypto { Rijndael rijndael ; public Crypto ( ) { rijndael = Rijndael.Create ( ) ; rijndael.Key = Encoding.ASCII.GetBytes ( `` aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa '' ) ; ; rijndael.IV = Encoding.ASCII.GetBytes ( `` bbbbbbbbbbbbbbbb '' ) ; ; rijndael.Padding = PaddingMode.PKCS7 ; } public byte [ ] Encrypt ( object obj... | How to avoid extra memory use during encryption and decryption ? |
C# | I am using ThreadPool with the follwoing code : -I am not sure what does o= > does in this code . Can anyone help me out . | ThreadPool.QueueUserWorkItem ( o = > MyFunction ( ) ) ; | What is = > operator in this code |
C# | OK OK , I know this is a hack , but this was for a tiny data-manipulation project and I wanted to play around . ; - ) I was always under the impression that the compiler would examine all anonymous types used in a C # program and if the properties were the same , it would only create one class behind the scenes.So let ... | var smallData1 = new smallData1 ( ) .GetData ( ) .Select ( x = > new { Name = x.NAME , x.ADDRESS , City = x.CITY , State = x.STATE , Zip = x.ZIP , Country = x.COUNTRY , ManagerName = x.MANAGER_NAME , ManagerID = x.MANAGER_ID } ) ; var smallData2 = new smallData2 ( ) .GetData ( ) .Select ( x = > new { x.Name , x.ADDRESS... | Compiler optimizations of anonymous types |
C# | I 'm looking for some kind of OffsetTime support in NodaTime , but am not seeing anything . I am receiving data in a format such as `` 17:13:00+10:00 '' . I am to treat this as a time offset , applying it to a given date ( which the user is in control of ) to arrive at a local time for display purposes.The best I 've b... | // the date for this OffsetDateTime will be 1/1/2000var parsed = OffsetDateTimePattern.CreateWithInvariantCulture ( `` HH : mm : sso < G > '' ) .Parse ( input ) .Value ; var desiredLocalDate = new LocalDate ( 2017 , 06 , 13 ) ; var adjusted = new OffsetDateTime ( new LocalDateTime ( desiredLocalDate.Year , desiredLocal... | OffsetTime in NodaTime |
C# | I came across the following piece of code during a code review.My intuition is telling me that this is n't following proper OOP.I 'm thinking that instead the LoadObject method should return a new SomeObject object , instead of modifying the one passed into it . Though I ca n't really find a proper explanation of why t... | public void someMethod ( ) { ... var someObject = new SomeObject ( ) ; LoadSomeObject ( reader , someObject ) ; } private void LoadSomeObject ( SqlDataReader reader , SomeObject someObject ) { someObject.Id = reader.GetGuid ( 0 ) ; } | Returning a new Object vs modifying one passed in as a parameter |
C# | I have some domain classes that look something like this , that I want to model with Code First ( in EF 4.3 ) .In every example I see though , foreign object references are added in the Foo class . Can my Foo class be agnostic of the Bar and Baz class , or do I really need to do something like this ? According to this ... | public class Foo { // ... } public class Bar { // ... public Foo Foo { get ; set ; } } public class Baz { // ... public Foo Foo { get ; set ; } } public class Foo { // ... public virtual Bar { get ; set ; } public virtual Baz { get ; set ; } } | Why do Code First classes need navigation properties ? |
C# | I can´t remove an element from an IEnumerable list , but this list is a reference to a List , a private attribute of an other class.If I put personsCollection.Remove ( theElement ) in the same class ( class Manager ) , it works perfect , but I need to delete the element since the other class ( class ManagerDelete ) . P... | class Other { //Some code public IEnumerable < Person > SearchByPhone ( string value ) { return from person in personCollection where person.SPhone == value select person ; } } class ManagerDelete { //Some codeIEnumerable < Person > auxList= SearchByPhone ( value ) ; //I have a method for delete here } class Manager { ... | Delete an element from a generic list |
C# | I 'm currently working on an upgrade to a project that extensively uses COM / MFC / ( who knows how many other technologies ) . As part of the upgrade , we 're trying to move as much functionality as we can into managed C # code , but unfortunately some stuff just ca n't move ( for reasons I wo n't go into ) . One of t... | MyComInterfaceInCS myObj = null ; try { world.GetTD_MyComInterfaceInCS ( ) ; } catch ( COMException comException ) { int pointerValue = Marshal.GetHRForException ( comException ) ; IntPtr myObjPointer = new IntPtr ( pointerValue ) ; myObj = ( MyComInterfaceInCS ) Marshal.GetObjectForIUnknown ( myObjPointer ) ; } | Get a COM object to throw an exception on any result except S_OK ( 0 ) in C # |
C# | I am creating an extension method that performs a test on an object to see if it has a specific custom attribute . I want to create a unit test for my extension method . How can I assert that the test in the extension method should fail ? Basically , the ShouldValidateTheseFields does reflection and asserts that it sho... | [ Test ] public void ShouldFailIfEmailAttributeMissingFromFieldName ( ) { // -- Arrange var model = new { Field = 1 } ; // -- Act model.ShouldValidateTheseFields ( new List < FieldValidation > { new EmailAddressFieldValidation { ErrorId = 1 , ErrorMessage = `` Message '' , FieldName = nameof ( model.Field ) } } ) ; // ... | Asserting that a system under test should throw an assertion exception |
C# | Assume I have an interface such asTIn being contra-variant , and TOut being co-variant.Now , I want callers to be able to specify some function to be executed on the input 's value , so naïvely I would add the following method to the interface : which … does not work . TIn is now required to be covariant , and TOut con... | public interface IInterface < in TIn , out TOut > { IInterface < TIn , TOut > DoSomething ( TIn input ) ; } IInterface < TIn , TOut > DoSomethingWithFunc ( Func < TIn , TOut > func ) ; public delegate TOut F < in TDlgIn , out TDlgOut > ( TDlgIn input ) ; public interface IInterface < in TIn , out TOut > { IInterface < ... | Co/contravariance with Func < in T1 , out TResult > as parameter |
C# | I am trying to convert List to json . Structure is as follow : This is producing the result as expected : How can I get the results like : - | public class ResourceCollection { public string Name { get ; set ; } public Resources Resources { get ; set ; } } public class Resources { public string en { get ; set ; } } List < ResourceCollection > liResourceName = new List < ResourceCollection > ( ) ; //section to add the objects in liststring json = JsonConvert.S... | How to skip property name in json serialization ? |
C# | I 'm need to hash against a member variable instead of the class , so I do n't check if the reference is in the dictionary . Without overriding the defaults , it wo n't find an identical Value , but only return if it finds the same exact instance of HashedType , such that this code fails.Definition of HashedType : It l... | Dictionary.Add ( new HashedType ( 4 ) ) ; Dictionary.Contains ( new HashedType ( 4 ) ) ; // fails to find 4 HashedType { public HashedType ( Int32 value ) { Value = value ) ; } public HashedType ( String value ) { Value = value ) ; } public object Value ; public void Serialize ( Serializer s ) { if ( Value.GetType ( ) ... | Advantage of deriving external class from IEqualityComparer < > over overriding GetHashCode and Equals |
C# | my problem is the following . I have made a code design for a home project which is apparently not working . Maybe you can help me to figure out where the `` code smell '' comes from.Ok let 's start : I have defined some classes to wrap around different kind of archive types : To handle with those archives , I defined ... | public abstract class Archive { } public class ZipArchive : Archive { } public class TarArchive : Archive { } public abstract class ArchiveManager < T > where T : Archive { public abstract void OpenArchive ( T archive ) ; } public class ZipArchiveManager : ArchiveManager < ZipArchive > { public override void OpenArchiv... | Declaration of a abstract generic type variable |
C# | I am trying to do the following with Entity Framework 6 and Code First : The result however is : Unable to determine the principal end of an association between the types 'Step ' and 'Step ' . The principal end of this association must be explicitly configured using either the relationship fluent API or data annotation... | public class Step { public int Id { get ; set ; } public Step NextStepSuccess { get ; set ; } public Step NextStepFailure { get ; set ; } } | Multiple self referencing in Entity Framework fails with `` principal end '' error |
C# | I 'm following the await tutorial on the MSDN , and I 'm trying to figure out the difference between using await as a statement versus using await as an expression . This whole async-await thing is bending my mind and I ca n't find any examples for this particular case.Basically , I wanted to see how to use multiple aw... | private async void button1_Click ( object sender , EventArgs e ) { // Using await as an expression string result_a = await WaitAsynchronouslyAsync ( ) ; string result_b = await WaitAsynchronouslyAsync ( ) ; // This takes six seconds to appear textBox1.Text = result_a + Environment.NewLine ; textBox1.Text += result_b ; ... | await statement vs. expression |
C# | If I have two types of rows : header rows and data rows . and any row should compose of 18 columns.The number of data rows is based on the number of header rows for example : and so onI want to loop over the columns of the data rows and map to the related header col data : Let 's take The second example : I have two he... | If I have 2 header rows , I should have ( 2 datarows : the first one map to the first header row , the second one map to the second header row + 2 datarows : the first one map to the first header row , the second one map to the second header row + 1 data rows for total : maps to the first header row ) = 5 datarows per ... | How to loop conditionally to map header rows to data rows |
C# | I 'm worried about the correctness of the seemingly-standard pre-C # 6 pattern for firing an event : I 've read Eric Lippert 's Events and races and know that there is a remaining issue of calling a stale event handler , but my worry is whether the compiler/JITter is allowed to optimize away the local copy , effectivel... | EventHandler localCopy = SomeEvent ; if ( localCopy ! = null ) localCopy ( this , args ) ; if ( SomeEvent ! = null ) SomeEvent ( this , args ) ; | Events and multithreading once again |
C# | I 'm trying to implement some functionality that was formerly provided via an Excel sheet into a C # application , but the probability mass function of Accord.NET differs for some reason from the excel function.In excel the probabilty mass function , is used this wayWhen I try it with Accord.NETBut the cumulative distr... | =BINOM.DIST ( 250 ; 3779 ; 0.0638 ; FALSE ) Result : 0.021944019794458 var binom = new BinomialDistribution ( 3779 , 0.0638 ) ; binom.ProbabilityMassFunction ( 250 ) ; // Result : Infinity =BINOM.DIST ( 250 ; 3779 ; 0.0638 ; TRUE ) Result : 0.736156366002849 var binom = new BinomialDistribution ( 3779 , 0.0638 ) ; bino... | Accord.Net binomial probability mass function result differs from Excel result |
C# | Trying to understand .net 's memory model when it comes to threading . This question is strictly theoretical and I know it can be resolved in other ways such as using a lock or marking _task as volatile.Take the following piece of code for example : Now make the following assumptions : Run can be called multiple times ... | class Test { Task _task ; int _working = 0 ; public void Run ( ) { if ( Interlocked.CompareExchange ( ref _working , 1 , 0 ) == 0 ) { _task = Task.Factory.StartNew ( ( ) = > { //do some work ... } ) ; _task.ContinueWith ( antecendent = > Interlocked.Exchange ( ref _working , 0 ) ) ; } } public void Dispose ( ) { if ( I... | Threading & implicit memory barriers |
C# | Is there a way to get the underlying variable name of a target object in a Visual Studio debugger visualizer ? The built-in string visualizer does it : Clicking on the visualizer icon for myStr , you will see the `` Expression '' text box shows `` myStr '' . How can I get this in my own visualizers ? | string myStr = `` abc\ndef '' ; Debugger.Break ( ) ; | get variable name in debugger visualizer |
C# | That is , in C , we can define a function like : and it will return a higher number every time it is called . Is there an equivalent keyword in C # ? | func ( ) { static int foo = 1 ; foo++ ; return foo ; } | Does there exist a keyword in C # that would make local variables persist across multiple calls ? |
C# | Recently , I came across some code that looked like this : Calling Test.Factory ( ) results in a Test object with a Things collection containing both `` First '' and `` Second '' .It looks like the line Things = { `` Second '' } calls the Add method of Things . If the ICollection is changed to an IEnumerable , there is... | public class Test { public ICollection < string > Things { get ; set ; } public Test ( ) { Things = new List < string > { `` First '' } ; } public static Test Factory ( ) { return new Test { Things = { `` Second '' } } ; } } var test = new Test ( ) ; test.Things = { `` Test '' } ; | Syntactic sugar for adding items to collections in object initialisers |
C# | I have an array x [ ] containing data . Also there is an array of `` system states '' c [ ] . The process : Is there any efficient way to find the values of f1 and f2 on 2-core system using 2 parallel threads ? I mean the following ( in pseudo-code ) : f1 and f2 are not time consumptive , but have to be calculated many... | for ( i = 1 ; i < N ; i++ ) { a = f1 ( x [ i ] + c [ i-1 ] ) ; b = f2 ( x [ i ] + c [ i-1 ] ) ; c [ i ] = a + b ; } thread_1 { for ( i = 1 ; i < N ; i++ ) a = f1 ( x [ i ] + c [ i-1 ] ) ; } thread_2 { for ( i = 1 ; i < N ; i++ ) { b = f2 ( x [ i ] + c [ i-1 ] ) ; c [ i ] = a + b ; //here we somehow get a { i } from thr... | Synchronous Parallel Process in C # / C++ |
C# | I 'm writing a Connect4 game with an AI opponent using adversarial search techniques and I have somewhat run into a wall . I feel that I 'm not far from a solution but that there 's perhaps a problem where I 'm switching perspectives ( as in : the perspective of which participant I 'm basing my evaluation scores on ) ,... | private int Negamax ( int depth , int alpha , int beta , Player player ) { Player winner ; if ( Evaluator.IsLeafNode ( game , out winner ) ) { return winner == player ? ( 10000 / depth ) : ( -10000 / depth ) ; } if ( depth == Constants.RecursionDepth ) { return Evaluator.Evaluate ( game , depth , player ) ; } foreach (... | Adverserial search troubles |
C# | I have a bunch of users , with a given start and end time , e.g . : I want to put them into buckets , based on times that they overlap ( based on a configurable threshold , e.g. , they need to overlap at least half an hour ) . I want buckets to be ideally 4 items big , but any range from 2-5 is acceptable.In the exampl... | { Name = `` Peter '' , StartTime = `` 10:30 '' , EndTime = `` 11:00 '' } , { Name = `` Dana '' , StartTime = `` 11:00 '' , EndTime = `` 12:30 '' } , { Name = `` Raymond '' , StartTime = `` 10:30 '' , EndTime = `` 14:00 '' } , { Name = `` Egon '' , StartTime = `` 12:00 '' , EndTime = `` 13:00 '' } , { Name = `` Winston ... | Is there a standard algorithm to balance overlapping objects into buckets ? |
C# | I have the following functionNow if T is en IEnumerable < > I want to have a different behaviour so I made a second functionWhen I invoke it like thisHowever when I invoke it like thisIt goes to the first one.Why does this happen and what is the best construction to solve this ? UPDATEI build a new example with the pro... | public static T Translate < T > ( T entity ) { ... . } public static IEnumerable < T > Translate < T > ( IEnumerable < T > entities ) { ... . } IEnumerable < string > test = new List < string > ( ) .AsEnumerable ( ) ; Translate ( test ) ; Func < IEnumerable < string > > func = ( ) = > new List < string > ( ) .AsEnumera... | C # more specific version on generic function |
C# | In our company there are thousands ( ! ) of cars . each car has a GPS device which sends periodically ( cycle ) its location.So each Cycle contains : List < Cars > ( cars that sent location – corresponding to the CycleNum ) CycleNum which is Cycle numberCycleNum is determined by a server.So for example in CycleNum=1 , ... | static int TotalCycles=0 ; class Car { public int CarId ; public int Location ; } class Cycle { public int CycleNum ; public List < Car > Cars ; public Cycle ( ) { CycleNum= ( ++TotalCycles ) ; } } List < Cycle > LstCyclces = new List < Cycle > ( ) ; Cycle cycle =null ; cycle = new Cycle ( ) ; //cycle 1 cycle.Cars = ne... | Linq fast intersect query - enhancement ? |
C# | Is it possible to define a function in a way that it basically returns itself as a delegate ? For example , if this was valid syntax : Then I could chain method calls together like this . | public class Scrub { public NotNull NotNull < T > ( T value , string name ) { if ( value == null ) throw new ArgumentNullException ( name ) ; return NotNull ; } } Scrub.NotNull ( param1 , nameof ( param1 ) ) ( param2 , nameof ( param2 ) ( param3 , nameof ( param3 ) ) ; | Function to return a function that returns a function , etc |
C# | I 'm used to write code like this in C # : This is the way I translated it in F # ( obj being a list ) : Is there any way to do this in F # without using a mutable variable ? Is there a more 'elegant ' way to handle this situation in F # ? Thank you ! | SomeObj obj ; try { // this may throw SomeException obj = GetSomeObj ( ) ; } catch ( SomeException ) { // Log error ... obj = GetSomeDefaultValue ( ) ; } obj.DoSomething ( ) ; let mutable obj = [ ] try obj < - getSomeObjwith | ex - > // Log ex obj < - getSomeDefaultValuedoSomething obj | How to write this C # code in F # |
C# | I am having a design problem and I know there has to be a way to make it work . I tried the solutions here : Annoying auto scroll of partially displayed items in WPF ListView But they didnt work for me because I am not allowed to work in the code-behind.I have a list of items from a wpf ListBox . like this : when I try... | < ListBox Grid.Column= '' 0 '' Grid.Row= '' 1 '' Name= '' RequestCheckoutV '' ItemsSource= '' { Binding Path=CheckoutVM , Mode=TwoWay , IsAsync=True } '' SelectedItem= '' { Binding Path=SelectedPermit } '' BorderThickness= '' 0 '' KeyboardNavigation.TabNavigation= '' Continue '' > < ListBox.ItemContainerStyle > < Style... | Selecting a partially displayed WPF checkbox |
C# | I 've a web site which writes a date like this : In both my PC ( Windows 7 , Service Pack 1 , Spanish culture ) and the server ( Windows Server 2012 , English Culture ) the MvcApplication.Language is es so the culture I get from the list is : es-ES.I 'd expect they both write the same string ( they have different cultu... | CultureInfo cultureInfo = CultureInfo.GetCultures ( CultureTypes.AllCultures ) .FirstOrDefault ( c = > string.Equals ( c.TwoLetterISOLanguageName , MvcApplication.Language ) ) ; return string.Concat ( date.Day , `` . `` , cultureInfo.DateTimeFormat.GetAbbreviatedMonthName ( date.Month ) ) ; | Instances of CultureInfo ( from same culture ) changing based on OS |
C# | I am trying to split using Regex.Split strings like this one : We have the following 'reserved words ' : NAME , COURSE , TEACHER , SCHEDULE , CAMPUS . It is required to split the original string into : The criteria for Split is : to have the simple quote , followed by one or more spaces , followed by a 'reserved word '... | string criteria = `` NAME='Eduard O ' Brian ' COURSE='Math II ' TEACHER = 'Chris Young ' SCHEDULE= ' 3 ' CAMPUS= ' C-1 ' `` ; NAME='Eduard O ' Brian'COURSE='Math II'TEACHER = 'Chris Young'SCHEDULE= ' 3'CAMPUS= ' C-1 ' var match = Regex.Split ( criteria , @ '' ' [ \s+ ] ( [ NAME ] | [ COURSE ] | [ TEACHER ] | [ SCHEDULE... | C # RegEx.Split delimiter followed by specific words |
C# | UpdateUploaded sample project : https : //github.com/subt13/BugSamplesI have reproduced an error that has been occurring in a Windows 10 UAP application that utilizes the MVVMLight framework . I receive the error below during navigation while the CPU is under heavy load ( ~20-25 % ) and the page is `` heavy '' ( large ... | private async void ExecuteLoadDataCommandAsync ( ) { // cause the app to slow done . var data = await Task.Run ( ( ) = > GetData ( ) ) ; if ( data ! = null ) { this.Data.Clear ( ) ; foreach ( var item in data ) { this.Data.Add ( new AnotherVM ( item ) ) ; } } // have the select job command rerun its condition this.Sele... | RaiseCanExecuteChanged COM Exception during Navigation ? |
C# | It 's possible to determine memory usage ( according to Jon Skeet 's blog ) like this : It prints Memory used : 16 bytes ( I 'm running x64 machine ) .Consider we change Point declaration from class to struct . How then to determine memory used ? Is is possible at all ? I was unable to find anything about getting stack... | public class Program { private static void Main ( ) { var before = GC.GetTotalMemory ( true ) ; var point = new Point ( 1 , 0 ) ; var after = GC.GetTotalMemory ( true ) ; Console.WriteLine ( `` Memory used : { 0 } bytes '' , after - before ) ; } # region Nested type : Point private class Point { public int X ; public i... | .NET , get memory used to hold struct instance |
C# | I am making an app in windows store and having a problem in writing xml in created xml file.I have followed this Editing XML file in Windows Store App but it did n't work for me.I want this xml to be wrote in my xml file on button click.Any alternate way for this stuff.. my current file is this : Here is what I have tr... | < drink > < drinkImage > ck.png < /drinkImage > < drinkTitle > COKE < /drinkTitle > < drinkDescription > ( 1793-1844 ) < /drinkDescription > < /drink > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < drinks > < drink > < drinkImage > pepsi.png < /drinkImage > < drinkTitle > PEPSI < /drinkTitle > < drinkDescripti... | Edit XML file in Windows Store app |
C# | I have a User class . One of the properties needs to be an `` associated '' user , so it 's type needs to be User . Right now when I initialize the class , I get a stack overflow when it tries to initialize the Associated property . Current code : Is this doable or am I barking up the wrong tree ? | public class User { public User ( ) { this.Associated = new User ( ) ; } public User Associated { get ; set ; } } | Initializing a new class in its own constructor |
C# | I recently discovered the following code below to effectively run lots of IO bound tasks ( see link ) .http : //blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspxI 'm under the impression the following are true : this is much better than using Parallel.ForEach because the work is not CPU bound.ForEachAsync will ... | public static Task ForEachAsync < T > ( this IEnumerable < T > source , int dop , Func < T , Task > body ) { return Task.WhenAll ( from partition in Partitioner.Create ( source ) .GetPartitions ( dop ) select Task.Run ( async delegate { using ( partition ) while ( partition.MoveNext ( ) ) await body ( partition.Current... | What do I specify as the Dop parameter for ForEachAsync extension method ? |
C# | I took the code of DCL from Joe Duffy 's book 'Concurrent programming on windows'it is said marking m_value volatile can prevent writes reordering that will leads to other threads getting 'non null object with uninitialized fields ' . If the problem happens just because the possible writes reordering , can I just use '... | class LazyInit < T > where T : class { private volatile T m_value ; private object m_sync = new object ( ) ; private Func < T > m_factory ; public LazyInit ( Func < T > factory ) { m_factory = factory ; } public T value { get { if ( m_value == null ) { lock ( m_sync ) { if ( m_value == null ) { m_value = m_factory ( ) ... | What kind of 'volatile ' operation is needed in Double checked locking in .NET |
C# | While reading Microsoft documentation , I stumbled on such an interesting code sample : It means you can cast your generic to the interface explicitly but not to the class unless you have a constraint . Well , I still can not understand the logic behind the decision as both interface and class type castings are throwin... | interface ISomeInterface { ... } class SomeClass { ... } class MyClass < T > { void SomeMethod ( T t ) { ISomeInterface obj1 = ( ISomeInterface ) t ; //Compiles SomeClass obj2 = ( SomeClass ) t ; //Does not compile } } class MyOtherClass { ... } class MyClass < T > { void SomeMethod ( T t ) { object temp = t ; MyOtherC... | Why there is a restriction for explicit casting a generic to a class type but there is no restriction for casting a generic to an interface type ? |
C# | I 'm looking to get a value from anFor logging purposes I need to be able to fish out that guid.I tried the following code , which I feel is somewhat close to what I 'm looking for , but not quite.Now , ConstantExpression exposes a member 'Value ' , which does contain what I 'm looking for , but I 'm a bit puzzled how ... | var guid = Guid.Parse ( `` SOMEGUID-GUID-GUID-GUID-SOMEGUIDGUID '' ) ; Expression < Func < Someobject , bool > > selector = x = > x.SomeId == guid ; BinaryExpression binaryExpression = ( BinaryExpression ) selector.Body ; MemberExpression memberExpression = ( MemberExpression ) ( ( UnaryExpression ) binaryExpression.Ri... | Get value from a ConstantExpression |
C# | Can I retrieve basic information about all collections in a MongoDB with F # ? I have a MongoDB with > 450 collections . I can access the db with I had considered trying to just get all collections then loop through each collection name and get basic information about each collection with and but the db.GetCollection (... | open MongoDB.Bsonopen MongoDB.Driveropen MongoDB.Driver.Core open MongoDB.FSharpopen System.Collections.Genericlet connectionString = `` mystring '' let client = new MongoClient ( connectionString ) let db = client.GetDatabase ( name = `` Production '' ) let collections = db.ListCollections ( ) db.GetCollection ( [ nam... | Getting general information about MongoDB collections with FSharp |
C# | I will start working on xamarin shortly and will be transferring a lot of code from android studio 's java to c # .In java I am using a custom classes which are given arguments conditions etc , convert them to SQL statements and then loads the results to the objects in the project 's modelWhat I am unsure of is wether ... | List < Customer > customers = ( new CustomerDAO ( ) ) .get_all ( ) List < Customer > customers = ( new CustomerDAO ( ) ) .get ( new Condition ( CustomerDAO.Code , equals , `` code1 '' ) var customers = from customer in ( new CustomerDAO ( ) ) .get_all ( ) where customer.code.equals ( `` code1 '' ) select customer Selec... | How does linq actually execute the code to retrieve data from the data source ? |
C# | I 'm trying to get started with JSIL . I 've followed the directions as far as I understand . I have a very basic C # dummy project with the code : I 've compiled this with jsilc , and created a website that hosts this along with the jsil scripts . My html initializes this : but ... I ca n't access the library . The co... | namespace TestLib { public class MagicType { public int Multiply ( int x , int y ) { // test instance method return x * y ; } public static int Add ( int x , int y ) { // test static int method return x + y ; } } } < script type= '' text/javascript '' > var jsilConfig = { libraryRoot : '/js/jsil/ ' , scriptRoot : '/js/... | How to access a basic JSIL library ( from C # ) in a web page ? |
C# | I 've this code I expected the output to be x = 57 and y = 94 . However , when executed it gave me 56 and 93.For some reason the post increment operator is not getting executed in line 3.Is this because we are assigning the result of expressing in line 3 to x itself ? Are there any other scenarios where the post increm... | static void Main ( string [ ] args ) { int x = 20 ; int y = 35 ; x = y++ + x++ ; y = ++y + ++x ; Console.WriteLine ( x ) ; Console.WriteLine ( y ) ; Console.ReadLine ( ) ; } | Post increment question |
C# | Say you have 3 classes that implement IDisposable - A , B and C. Classes A and B are both dependent on class C. Would it be correct to say that classes A and B 's typical implementation of Dispose ( ) would be : If there 's an instance of A and and instance of B that share the same instance of C , how would you overcom... | public void Dispose ( ) { if ( m_C ! = null ) m_C.Dispose ( ) ; } | A problematic example of the IDisposable pattern ? |
C# | Am getting the below error when I try to download the a .pdf file from a url through my .exe file . The server committed a protocol violation . Section=ResponseHeader Detail=CR must be followed by LFbut the same is getting downloaded when I try to debug the code from visual studio . I am totally lost , no clue of whats... | < ? xml version= '' 1.0 '' ? > < configuration > < system.net > < settings > < httpWebRequest useUnsafeHeaderParsing= '' true '' / > < /settings > < /system.net > < /configuration > public class CookieAwareWebClient : WebClient { private CookieContainer cc = new CookieContainer ( ) ; private string lastPage ; protected... | File is downloading through visual studio but not through .exe |
C# | When using IndexOf to find a char which is followed by a large valued char ( e.g . char 700 which is ʼ ) then the IndexOf fails to recognize the char you are looking for.e.g.In this code , index should be 2 , but it returns 6.Is there a way to get around this ? | string find = `` abcʼabcabc '' ; int index = find.IndexOf ( `` c '' ) ; | string.IndexOf ( ) not recognizing modified characters |
C# | Our current web portal at work was a port from a classic ASP codebase . Currently , all pages in our project extend a custom Page class called PortalPage . It handles login/logout , provides access to a public User object for the currently authenticated user , and adds the standard page header and footer to all of our ... | HtmlGenericControl wrapperDiv = new HtmlGeneric ( `` div '' ) ; HtmlAnchor bannerLink = new HtmlAnchor ( ) ; HtmlImage banner = new HtmlImage ( ) ; bannerLink.HRef = `` index.aspx '' ; banner.Src = `` mybanner.png '' ; banner.Alt = `` My Site '' ; bannerLink.Controls.Add ( banner ) ; wrapperDiv.Controls.Add ( bannerLin... | Designing all pages completely in the codebehind ? |
C# | I implemented an autocomplete search box on my asp.net mvc4 site . I am currently able to have the box return results that update as i type in the search box . I also am dynamically generating `` category '' buttons based on the result `` type IDs '' and inserting them in a header that appears when the autocomplete pro... | @ model myproject.Models.Search_Term @ Scripts.Render ( `` ~/bundles/jquery '' ) < script type= '' text/javascript '' > //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // autopopulate input boxes ///////////////////////////////////////////////////////... | How to use button within autocomplete dropdown to further filter the already-displayed results |
C# | As practice for writing fluent APIs , I thought I 'd make the following compile and run : The idea is .When will test each element in the enumeration , and if it passes the predicate , to have the action run . If the predicate fails , the item is passed down the chain.The graph I came up with was : I am running into an... | static void Main ( string [ ] args ) { Enumerable.Range ( 1 , 100 ) .When ( i = > i % 3 == 0 ) .Then ( i = > Console.WriteLine ( `` fizz '' ) ) .When ( i = > i % 5 == 0 ) .Then ( i = > Console.WriteLine ( `` buzz '' ) ) .Otherwise ( i = > Console.WriteLine ( i ) ) .Run ( ) ; Console.ReadLine ( ) ; } public static class... | What is the fluent object model to make this work ? |
C# | I stumbled upon a strange behavior of Convert.FromBase64String in .NET 4.7.2 . Normally it would throw an exception when the padding is not correct . But I found a case where adding another padding character produces an incorrect result instead of an exception . In this case correct is [ 97 , 97 ] or `` aa '' in a stri... | var correct = Convert.FromBase64String ( `` YWE= '' ) ; var incorrect = Convert.FromBase64String ( `` YWE== '' ) ; Base64.strict_decode64 `` YWE= '' Base64.strict_decode64 `` YWE== '' ArgumentError : invalid base64from /usr/local/Cellar/ruby/2.6.1/lib/ruby/2.6.0/base64.rb:74 : in ` unpack1 ' | Decoding Base64 in C # sometimes gives incorrect result with one extra padding character |
C# | This probably applies to other places , but in WinForms , when I use binding I find many methods want to take the name of the property to bind to . Something like : The big problem I keep having with this is that `` Name '' and `` Age '' are specified as strings . This means the compiler is no help if someone renames o... | class Person { public String Name { get { ... } set { ... } } public int Age { get { ... } set { ... } } } class PersonView { void Bind ( Person p ) { nameControl.Bind ( p , '' Name '' ) ; ageControl.Bind ( p , '' Age '' ) ; } } ageControl.Bind ( p , stringof ( p.Age ) .Name ) ; | Is there a way of making C # binding work statically ? |
C# | I really enjoy to be able to do this in C # : Whereas in Java I would have done it like that : Notice that the Java code tells the type of what is returned ( Pizza instances ) . The C # code does n't . It bugs me , especially in situations where others programmers do n't have access to the source code . Is there a way ... | IEnumerable GetThePizzas ( ) { yield return new NewYorkStylePizza ( ) ; yield return new SicilianPizza ( ) ; yield return new GreekPizza ( ) ; yield return new ChicagoStylePizza ( ) ; yield return new HawaiianPizza ( ) ; } Collection < Pizza > getThePizzas ( ) { ArrayList < Pizza > pizzas = new ArrayList < Pizza > ( ) ... | Strongly-typed method interface using yield return |
C# | I 'm reading an OfficeOpenXml.ExcelWorksheet and getting the ArgumentOufOfRangeException on the middle of the Collection . I 'm reading like this process.Information = sheet.Cells [ line , i++ ] .Text ; . On this line i = 22 while the sheet.Dimension.Column = 28 . When I 'm debugging and enumerate the collection I see ... | at System.Text.StringBuilder.Insert ( Int32 index , Char* value , Int32 valueCount ) at System.Text.StringBuilder.Insert ( Int32 index , Char value ) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.ExcelFormatTranslator.ToNetFormat ( String ExcelFormat , Boolean forColWidth ) at OfficeOpenXml.Style.XmlAccess.Exce... | C # ArgumentOutOfRangeException while reading ExcelWorksheet |
C# | I have the following method : Right now , a user of this method has to use it like this : Why do I have to specify TResult in the method defintion ? The compiler already knows TResult since I specified it in TGenericType . Ideally ( if the C # compiler was a little smarter ) , my method would look like this : So the us... | public TResult Get < TGenericType , TResult > ( ) where TGenericType : SomeGenericType < TResult > where TResult : IConvertible { // ... code that uses TGenericType ... // ... code that sets someValue ... return ( TResult ) someValue ; } //Notice the duplicate int type specificationint number = Get < SomeGenericType < ... | How to get the C # compiler to infer generic types ? |
C# | Expanding on my previous post , I am still writing Towers of Hanoi . After having a wonderful solution explained of how to draw the rings on the pegs , I still have one question that I have been fiddling with for quite awhile now . Here is my PegClass : And here is my main method . This is the current output : My quest... | namespace Towers_Of_Hanoi { class PegClass { private int pegheight ; private int y = 3 ; int [ ] rings = new int [ 0 ] ; public PegClass ( ) { //this is the default constructor } public PegClass ( int height ) { pegheight = height ; } // other user defined functions public void AddRing ( int size ) { Array.Resize ( ref... | Towers of Hanoi : Moving Rings from Peg to Peg |
C# | I have a method that takes three parameters : List < Class1 > source , List < Class2 ) results , and DateTime endDate . I can see why the class coupling is four . However , it jumps to ten when I add this statement : My questions : What are the six new classes that were introduced by the LINQ statement ? And since ten ... | var warnings = from s in source join r in results on s.Field1 equals r.Field1 into joined from j in joined.DefaultIfEmpty ( ) where j == null select string.Format ( `` { 0 } { 1 } '' , A_CONSTANT , s.Field2 ) ; | Why does Class Coupling jump when I use LINQ ? |
C# | I 'm wondering why this C # codeis compiled to ( Because it takes 3 bytes instead of the 9 required by ldc.i8 20 . See this for more information . ) while this codeis compiled to the 9-byte instructioninstead of this 3-byte sequence ( Using mono 4.8 . ) Is this a missed opportunity or the cost of the conv.i8 outbalance... | long b = 20 ; ldc.i4.s 0x14conv.i8 double a = 20 ; ldc.r8 20 ldc.i4.s 0x14conv.r8 | Why does the compiler optimize ldc.i8 and not ldc.r8 ? |
C# | I have the following classes defined : Now , in my global.asax , I 've defined the following Mapping in Application_Start ( ) .Lastly , in one of my controllers , I have the following code : The first time I call the Action on my controller and this mapping is run , everything works fine and the InstrumentNumber is cor... | public class ImageIndexModel { public string Description { get ; set ; } public string InstrumentNumber { get ; set ; } } public class ImageEditModel : ImageIndexModel { public int TotalCount = 0 ; } public class Clerk { //This is actually a class defined by LinqToSql public string Description { get ; set ; } public st... | Automapper maps correctly on first call but skips properties on second call |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.