lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | Parhaps a silly question ... I 'm new to C # and .Net.In the example for the SafeHandle class ( C # ) on MSDN , the code made me scratch my head a bit.My question is : How does the Win32 HANDLE from the C function CreateFile get into the MySafeFileHandle objects protected IntPtr `` handle '' variable ? The constructor ... | [ SecurityPermission ( SecurityAction.InheritanceDemand , UnmanagedCode = true ) ] [ SecurityPermission ( SecurityAction.Demand , UnmanagedCode = true ) ] internal class MySafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { private MySafeFileHandle ( ) : base ( true ) { } // other code here } [ SuppressUnmanagedCodeSe... | MSDN SafeHandle example |
C# | This very simple code does not work the same under Linux as it does on my Windows machine : This should produce an output likeIt works well in development and if published to Windows . If published for Linux it hangs after putting out 'Hello World ' . The await Task.Delay ( ) never returns . I 've tried with a fresh in... | class Program { async static Task Main ( string [ ] args ) { Console.WriteLine ( `` Hello World ! `` ) ; for ( int i = 0 ; i < 5 ; i++ ) { await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; Console.WriteLine ( `` '' + i ) ; } Console.WriteLine ( `` Bye bye '' ) ; } } Hello World01.. 4Bye bye | Can not await Task.Delay with .Net Core under Linux |
C# | I 'm working on an ASP.NET MVC app , designing the domain models , using ( testing ) the new EF Code First feature.I have an Activity entity that may or may not have a Deadline , what is the best way to approach it ? 1 property : or 2 properties : At first I thought of the first option , but then I started thinking tha... | public DateTime ? Deadline { get ; set ; } and check vs null before using public DateTime Deadline { get ; set ; } public bool HasDeadline { get ; set ; } | Whats better design/practice : Nullable property or 1 value property and 1 bool `` has '' property ? |
C# | I would like to write my own custom compound statements that have a similar mechanism to using and lock mechanisms where they have code injected at the beginning and end of the statement block before compilation . I have tried searching for questions who may have asked similar questions but I could not properly figure ... | StartContext ( 8 ) ; //make method callsEndContext ( ) ; DoSomethingInContext ( 8 ) { //make method calls } | Custom Compound statements in c # |
C# | I am using ASP.NET MVC 4 and Entity Framework 6 ( Code First ) and have some strange behaviour I do not want/like : I have an entity class Images which has a boolean property IsDeleted and now I would like to get the first 25 images , which are not deleted , so I used the following code : As this was very slow I invest... | IEnumerable < Image > items = db.Images.Where ( i = > ! i.IsDeleted ) .Take ( 25 ) ; | .Where ( i = > ! i.IsDeleted ) does not translate to SQL but .Where ( i = > i.IsDeleted.Equals ( false ) ) does |
C# | Using VS2010 and ReSharper 5I have a method which returns a System.ActionReSharper , for some reason , tends to show me a correction that the return type of the method should be mapped to System.Action < T > or one of its variants . It seems that it wo n't recognize the non-generic version ! VS complies and does n't co... | private Action ExtractFile ( ) { return delegate { MessageBox.Show ( `` Test '' ) ; } ; } | ReSharper always asks to change System.Action to System.Action < T > |
C# | I just saw this in a c # project : I consider myself new to C # ; any one can help what it 's meaning ? | public char this [ int index ] | “ Strange ” C # property syntax |
C# | Given a simple Hotel entity as an example : Please consider the following code in C # 5.0 : Both calls to Debug.Assert ( ) pass successfully . I do n't understand how after both tasks have completed , the instance of Hotel contains the assignment from both the methods that run in parallel.I thought that when await is c... | class Hotel { public int NumberOfRooms { get ; set ; } public int StarRating { get ; set ; } } public void Run ( ) { var hotel = new Hotel ( ) ; var tasks = new List < Task > { SetRooms ( hotel ) , SetStars ( hotel ) } ; Task.WaitAll ( tasks.ToArray ( ) ) ; Debug.Assert ( hotel.NumberOfRooms.Equals ( 200 ) ) ; Debug.As... | How does C # Task.WaitAll ( ) combine object states into one ? |
C# | I am pulling JSON data from several remote servers concurrently over HTTP , using a WCF service on both the client and server endpoints . I 'm noticing that for each successive request that starts asynchronously the length of time that http request takes is generally increasing , even if the amount of data is not neces... | : HttpRequest invoked . Elapsed : 325ms : HttpRequest invoked . Elapsed : 27437ms : HttpRequest invoked . Elapsed : 28642ms : HttpRequest invoked . Elapsed : 28496ms : HttpRequest invoked . Elapsed : 32544ms : HttpRequest invoked . Elapsed : 38073ms : HttpRequest invoked . Elapsed : 41231ms : HttpRequest invoked . Elap... | Concurrently downloading JSON data from remote service ( s ) |
C# | I 'd like to add parts of the source code to the XML documentation . I could copy & paste source code to some < code > elements , like this : Maintaining this will be painful . Are there other possibilities to add source code to the XML documentation in C # ? I am processing the XML documentation with Sandcastle and wo... | /// < summary > /// Says hello world in a very basic way : /// < code > /// System.Console.WriteLine ( `` Hello World ! `` ) ; /// System.Console.WriteLine ( `` Press any key to exit . `` ) ; /// System.Console.ReadKey ( ) ; /// < /code > /// < /summary > static void Main ( ) { System.Console.WriteLine ( `` Hello World... | How to make source code a part of XML documentation and not violate DRY ? |
C# | Having just spent over an hour debugging a bug in our code which in the end turned out to be something about the Enumerable.Except method which we did n't know about : or more generally : Looking at the MSDN page : This method returns those elements in first that do not appear in second . It does not also return those ... | var ilist = new [ ] { 1 , 1 , 1 , 1 } ; var ilist2 = Enumerable.Empty < int > ( ) ; ilist.Except ( ilist2 ) ; // returns { 1 } as opposed to { 1 , 1 , 1 , 1 } var ilist3 = new [ ] { 1 } ; var ilist4 = new [ ] { 1 , 1 , 2 , 2 , 3 } ; ilist4.Except ( ilist3 ) ; // returns { 2 , 3 } as opposed to { 2 , 2 , 3 } var ilist =... | why does Enumerable.Except returns DISTINCT items ? |
C# | Consider the following code : When I cancel the task using the provided CancelSource , output is : OnlyOnCanceledNoneas expected.When LongRunningMethod throws an Exception output is : OnlyOnFaultedNoneas expected.When LongRunningMethod completes output is : Noneso the ContinueWith with TaskContinuationOptions.OnlyOnRan... | MyTask = LongRunningMethod ( progressReporter , CancelSource.Token ) .ContinueWith ( e = > { Log.Info ( `` OnlyOnCanceled '' ) ; } , default , TaskContinuationOptions.OnlyOnCanceled , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( e = > { Log.Info ( `` OnlyOnFaulted '' ) ; } , default , TaskConti... | Task.ContinueWith ( ) executing but Task Status is still `` Running '' |
C# | I have the following : and I want to use the ! operator as follows : ( it 's an Enum ) I have tried : ... but I receive an error : Parameter type of this unary operator must be the containing typeAny ideas ? | MovingDirection.UP ; ! MovingDirection.Up ; // will give MovingDirection.Down public static MovingDirection operator ! ( MovingDirection f ) { return MovingDirection.DOWN ; } | Is there a way to implement unary operators for enum types ? |
C# | Possible Duplicate : How do I Unregister 'anonymous ' event handler I have code like this : How do I now disconnect the Format event ? | Binding bndTitle = this.DataBindings.Add ( `` Text '' , obj , `` Title '' ) ; bndTitle.Format += ( sender , e ) = > { e.Value = `` asdf '' + e.Value ; } ; | How to disconnect an anonymous event ? |
C# | Updated : See end of question for how I implemented the solution.Sorry for the poorly-worded question , but I was n't sure how best to ask it . I 'm not sure how to design a solution that can be re-used where most of the code is the exact same each time it is implemented , but part of the implementation will change eve... | public class OutboxManager { private List < OutboxMsg > _OutboxMsgs ; public void DistributeOutboxMessages ( ) { try { RetrieveMessages ( ) ; SendMessagesToVendor ( ) ; MarkMessagesAsProcessed ( ) ; } catch Exception ex { LogErrorMessageInDb ( ex ) ; } } private void RetrieveMessages ( ) { //retrieve messages from the ... | How should I model my code to maximize code re-use in this specific situation ? |
C# | After C # 5 introduced the async and await model for asynchronous programming , the C # community arrived at a naming convention to add an `` Async '' suffix to methods returning an awaitable type , like this : Many static code analyzers ( both Roslyn-based and non-Roslyn-based ) have since been written to depend on th... | interface Foo { Task BarAsync ( ) ; } interface Foo { // No `` Async '' suffix , indicating that the return value is not awaitable . IAsyncEnumerable < T > Bar < T > ( ) ; } interface Foo { // With `` Async '' suffix , indicating that the overall logic is asynchronous . IAsyncEnumerable < T > BarAsync < T > ( ) ; } | Is there a definitive naming convention for methods returning IAsyncEnumerable ? |
C# | I have created a Visual Studio Add-In that adds a form to an existing Project in the opened solution.This is how I create the form : After that I can successfully get the reference to the ProjectItem of the added form , then I can get a reference to the System.Windows.Forms.Form , and through this reference I can add a... | string templatePath = sol.GetProjectItemTemplate ( `` Form.zip '' , `` csproj '' ) ; //sol is an EnvDTE80.Solution2proj.ProjectItems.AddFromTemplate ( templatePath , formName ) ; //proj is an EnvDTE.Project Button btn = new Button ( ) ; btn.Text = `` my funky button '' ; btn.Name = `` newButton '' ; btn.Size = new Size... | Form wo n't save after creating it with EnvDTE |
C# | OK , that title is a little unclear , but I ca n't think of a better way of putting it , other than explaining it ... Say I have a class Animal , with a static , generic method : And I have subclasses Dog , Cat , Hamster etc . In order to get a Dog , I can write : orwhich is really the same thing . But it seems kinda s... | public static T Create < T > ( ) where T : Animal { // stuff to create , initialize and return an animal of type T } Dog d = Animal.Create < Dog > ( ) ; Dog d = Dog.Create < Dog > ( ) ; Dog d = Dog.Create ( ) ; Cat c = Cat.Create ( ) ; Hamster h = Hamster.Create ( ) ; | Is it possible to detect class context in an inherited static method ? |
C# | I have some configuration data that I 'd like to model in code as so : With this configuration set , I then need to do lookups on bazillion ( give or take ) { Key1 , Key2 , Key3 } tuples to get the `` effective '' value . The effective value to use is based on a Key/Priority sum whereby in this example : So a specifc q... | Key1 , Key2 , Key3 , Valuenull , null , null , 11 , null , null , 29 , null , null , 211 , null , 3 , 3null , 2 , 3 , 41 , 2 , 3 , 5 Key1 - Priority 10Key2 - Priority 7Key3 - Priority 5 given a key of { 1 , 2 , 3 } the value should be 5.given a key of { 3 , 2 , 3 } the value should be 4.given a key of { 8 , 10 , 11 } t... | How to build a `` defaulting map '' data structure |
C# | I have a MethodInfo passed in to a function and I want to do the followingBut this does n't work because the methodInfo has a specific generic type . For the example does work if I knew that the ICollection was always of type string.How can I check whether the MethodInfo is a ANY typed instance of the generic method wi... | MethodInfo containsMethod = typeof ( ICollection < > ) .GetMethod ( `` Contains '' ) ; if ( methodInfo.Equals ( containsMethod ) { // do something } MethodInfo containsMethod = typeof ( ICollection < string > ) .GetMethod ( `` Contains '' ) ; if ( methodInfo.Equals ( containsMethod ) { // do something } IList < string ... | How do I determine if a method is a generic instance of a generic method |
C# | This is a continuation of my question about downloading files in chunks . The explanation will be quite big , so I 'll try to divide it to several parts.1 ) What I tried to do ? I was creating a download manager for a Window-Phone application . First , I tried to solve the problem of downloading large files ( the expla... | if ( mediaFileLength > = delta ) // mediaFileLength is a length of downloaded chunk // Check file size using ( IsolatedStorageFileStream fileStream = isolatedStorageFile.OpenFile ( `` SomewhereInTheIsolatedStorage '' , FileMode.Open , FileAccess.Read ) ) { int currentFileSize = Convert.ToInt32 ( fileStream.Length ) ; i... | `` Where are my bytes ? '' or Investigation of file length traits |
C# | I have a table called visit with the following columns : I have the following SQL query : How can I convert this SQL into LINQ ? My entity name is dbcontext . Thanks in advance for any help . | visit_Idmember_Id visit_Date visit_Time visit_DateTime visit_Status values like ( accepted , refused ) string sql = @ '' SELECT CONCAT ( UPPER ( SUBSTRING ( visit_Status , 1 , 1 ) ) , SUBSTRING ( visit_Status FROM 2 ) ) as Status , COUNT ( ' x ' ) AS Visits FROM visits WHERE visit_Date BETWEEN '2001-09-08 ' AND '2009-0... | Convert SQL query to LINQ |
C# | I have a need for a simple AsyncLazy < T > which behaves exactly like Lazy < T > but correctly supports handling exceptions and avoids caching them.Specifically the issue I am running into is as follows : I can write a piece of code as such : Note the use of LazyThreadSafetyMode.PublicationOnly . If the initialization ... | public class TestClass { private int i = 0 ; public TestClass ( ) { this.LazyProperty = new Lazy < string > ( ( ) = > { if ( i == 0 ) throw new Exception ( `` My exception '' ) ; return `` Hello World '' ; } , LazyThreadSafetyMode.PublicationOnly ) ; } public void DoSomething ( ) { try { var res = this.LazyProperty.Val... | Prevent Lazy < T > caching exceptions when invoking Async delegate |
C# | Consider this code : The code compiles successfully . Then I 'm adding the nuget package `` itext7 7.0.4 '' , and now the compilation fails because of : The reason is that the itext7 library has an internal class with extension methods in the global namespace ( here it is ) .For some reason the compiler chooses an inac... | using System.Linq ; namespace ExtensionMethodIssue { static class Program { static void Main ( string [ ] args ) { var a = new [ ] { 1 } ; var b = new [ ] { 1 , 2 } .Where ( a.Contains ) .ToList ( ) ; var c = new [ ] { 1 , 2 } .Where ( i = > a.Contains ( i ) ) .ToList ( ) ; } } } //Error CS0122 : 'KernelExtensions.Cont... | C # compiler chooses wrong extension method |
C# | I 'm primarily a Java programmer , so this would be one of those `` what is this thing from Java equivalent to in C # '' questions . So , in Java , you can restrain a Class type argument at compile time to extend a certain super-class , like so : and evenYou can even chain multiple interfaces : How is this done in C # ... | public < T extends BaseClass > void foo ( Class < T > type ) { ... } public < T extends BaseClass > T foo ( Class < T > type ) { ... } public < T extends BaseClass & BaseInterface1 & BaseInterface2 > void foo ( Class < T > type ) { ... } abstract class BaseClass { abstract void Foo ( ) ; } class SubClass1 : BaseClass {... | Make sure Type instance represents a type assignable from certain class |
C# | Here I split the string into two string.For example , input : Helloworldoutput : Hello world.But now I need the output : dlrow olleH | string givenstring , outputString= '' '' ; int i , j = 0 ; Console.WriteLine ( `` Enter the string '' ) ; givenstring = Console.ReadLine ( ) ; i = ( givenstring.Length ) / 2 ; while ( j < i ) { outputString += givenstring [ j ] ; j++ ; } Console.WriteLine ( outputString ) ; outputString = string.Empty ; while ( i < giv... | Spliting a string into two words using while |
C# | In my _Layout page , I have got a search form and each controller has an index view . When the user clicks the search button , it searches in the current index view . I want to show the search field if the user is index view if they go to other views , I wanted to hide it . In my _Layout I am using JQuery at the moment... | < form asp-action= '' Index '' method= '' get '' class= '' navbar-form form-inline navbar-right '' > < input class= '' form-control mr-sm-2 '' id= '' search '' name= '' search '' type= '' search '' placeholder= '' Search '' aria-label= '' Search '' > < button class= '' btn btn-outline-success my-2 my-sm-0 '' id= '' Btn... | How to get the current Action name inside the View |
C# | After reading a question here about what things our computer could do in one second I made a little test I had in mind for a while and I 'm very surprised by the results . Look : Simple program to catch a null exception , takes almost one second to do 1900 iterations : Alternatively , checking if test == null before do... | for ( long c = 0 ; c < 200000000 ; c++ ) { try { test = null ; test.x = 1 ; } catch ( Exception ex ) { } } for ( long c = 0 ; c < 1900 ; c++ ) { test = null ; f ( ! ( test == null ) ) { test.x = 1 ; } } | Why this performance difference ? ( Exception catching ) |
C# | In this case I have a Grid with a lot controls inside it , buttons , canvas , drawing , animations , all bound to view-models , I would like to disable all the dataTriggers , triggers , bindings inside its children and children of children , etc. , when I set the visibility of the Grid to collapsed , so it is not wasti... | < ContentControl Visibility= '' Collapsed '' > < ContentControl.Template > < Grid Name= '' Heavy Animation control '' > < ! -- - animations , triggers , bindings , -- > < /Grid > < /ContentControl.Template > | How to disable all binding/triggering inside a ContentControl |
C# | The whole day I am trying to get this working.I am doing a dependency injection via this code : Everytime when I am executing this code I am getting the following error : I am really annoyed of that because I ca n't get it working and I have no clue about it . I am relatively new to Asp.Net and C # but this is how the ... | public Startup ( IApplicationEnviroment appEnv ) { var builder = new ConfigurationBuilder ( ) .SetBasePath ( appEnv.ApplicationBasePath ) .AddJsonFile ( `` config.json '' ) .AddEnvironmentVariables ( ) ; Configuration = builder.Build ( ) ; } # if DEBUG services.AddScoped < IMailService , DebugMailService > ( ) ; # else... | Dependency Injection IApplicationEnvironment Error |
C# | Put simply , I can create 2 dependency properties in a WPF control and put code in each property change notification to change the other property ( i.e PropA change sets PropB and PropB change sets PropA ) .I would expect this to disappear up its own backside but WPF seems to handle it nicely . That 's actually very ha... | < Window x : Class= '' WPFReentrancy1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < Grid > < TextBox Text= '' { Binding PropB , UpdateSourceTrigger=Prop... | Dependency property re-entrancy ( or : why does this work ? ) |
C# | I have a string that looks like that : And this class : And I want to create a List of Users with informations from that string.I have tried doing that : But I can only combine two lists using this code . Also , I have more than 4 values for each user ( the string above was just a short example ) .Is there a better met... | random text 12234another random text User infos : User name : JohnID : 221223Date : 23.02.2018Job : job1User name : AndrewID : 378292Date : 12.08.2017Job : job2User name : ChrisID : 930712Date : 05.11.2016Job : job3some random text class User { public string UserName { get ; set ; } public string ID { get ; set ; } pub... | Create a list of objects with initialized properties from a string with infos |
C# | Here are a list of aliases in C # ( compliments of What is the difference between String and string in C # ? ) : I can see bool through char being lowercase aliases , because they are primitive types.Why are object and string not capitalized , since they are complex types ? Is this an oversight by the developers , or i... | object : System.Objectstring : System.Stringbool : System.Booleanbyte : System.Bytesbyte : System.SByteshort : System.Int16ushort : System.UInt16int : System.Int32uint : System.UInt32long : System.Int64ulong : System.UInt64float : System.Singledouble : System.Doubledecimal : System.Decimalchar : System.Char | Why are the aliases for string and object in lowercase ? |
C# | I have tilt image capture by mobile . I want to cut section/portion of image in between two rectangles of both sides to find out circles in between them . I have all 4 co-ordinates of middle section like ( x0 , y0 ) , ( x1 , y1 ) , ( x2 , y2 ) , ( x3 , y3 ) . My Image is looks like , But crop function I have something ... | public static Bitmap CropImage ( int x , int y , int width , int height , Bitmap bitmap ) { Bitmap croppedImage ; var originalImage = bitmap ; { Rectangle crop = new Rectangle ( x , y , width , height ) ; croppedImage = originalImage.Clone ( crop , originalImage.PixelFormat ) ; } // Here we release the original resourc... | How to crop tilt image in c # |
C# | Ok , as I was poking around with building a custom enumerator , I had noticed this behavior that concerns the yieldSay you have something like this : What makes it possible underneath the compiler 's hood to execute the index ++ and the rest of the code in the while loop after you technically do a return from the funct... | public class EnumeratorExample { public static IEnumerable < int > GetSource ( int startPoint ) { int [ ] values = new int [ ] { 1,2,3,4,5,6,7 } ; Contract.Invariant ( startPoint < values.Length ) ; bool keepSearching = true ; int index = startPoint ; while ( keepSearching ) { yield return values [ index ] ; //The mind... | The wonders of the yield keyword |
C# | For my homework , I 'm implementing a course registration system for a university and I implemented a simple class for Curriculum with list of semesters and other properties like name of the department , total credits etc . But I 'm wondering if I can inherit this class from a Graph Data Structure with Edges and vertic... | public class Curriculum { public string NameOfDepartment { get ; set ; } public List < Semester > Semesters { get ; set ; } public bool IsProgramDesigned { get ; set ; } public Curriculum ( ) { IsProgramDesigned = false ; } // public string AddSemester ( Semester semester ) { | What Data Structure would you use for a Curriculum of a Department in a University ? |
C# | I have a function that accepts an Enum ( The base class ) as a parameter : However I ca n't for some reason cast it to int . I can get the name of the enumeration value but not it 's integral representation.I really do n't care about the type of the enumeration , I just need the integral value.Should I pass an int inst... | public void SomeFunction ( Enum e ) ; | How to cast an Enum to an int ? |
C# | Recently I 'm developing a software that parses and displays XML information from a website . Simple enough right ? I 'm getting LOADS of NullReferenceExceptions . For example , this method : I had to wrap an ugly as sin If around the actual foreach loop in order to prevent an exception.I feel I 'm just putting bandaid... | private void SetUserFriends ( List < Friend > list ) { int x = 40 ; int y = 3 ; if ( list ! = null ) { foreach ( Friend friend in list ) { FriendControl control = new FriendControl ( ) ; control.ID = friend.ID ; control.URL = friend.URL ; control.SetID ( friend.ID ) ; control.SetName ( friend.Name ) ; control.SetImage ... | I seem to have fallen into some massive , massive trouble with NullReferenceExceptions |
C# | I am adding image to the radtreeviewitem from resources programatically using the below code.and the image is displaying successfully . Now i need to add another image which needs to be displayed next to the first image in the radtreeviewitem.how to achieve it . ? Like the below image i need my treeviewitem to display ... | `` /myAssembley ; component/Resources/image1.png '' | How to show more that one image in the radtreeview item ( wpf - telerik ) |
C# | as per https : //www.mikesdotnetting.com/article/343/improved-remote-validation-in-razor-pagesI followed the tutorial and implemented the PageRemote . However it does not work if applied to a property of a model and I use the model as property . on my page | public class Draft { public int Id { get ; set ; } [ PageRemote ( ErrorMessage = `` Invalid data '' , AdditionalFields = `` __RequestVerificationToken '' , HttpMethod = `` post '' , PageHandler = `` CheckReference '' ) ] public string Reference { get ; set ; } } [ BindProperty ] public Draft Draft { get ; set ; } publi... | RazorPages Page Remote not working on model |
C# | Is this a bug or a feature ? All code below has been simplified for the sake of brevity and easy replication and does not actually do anything useful other than highlight the behavior.I have a class that includes an int named ID : In my controller , I have an Edit actionresult that takes a parameter called 'id ' : in m... | public class FooterLink { public int ID { get ; set ; } } public ActionResult Edit ( int id ) { return View ( new FooterLink ( ) { ID = 5 } ) ; //notice that I am explicitly setting the ID value here . } < % = Html.ActionLink ( `` Edit '' , `` Edit '' , new { id = 1 } ) % > < % = Html.TextBox ( `` ID '' , Model.ID ) % ... | Why is my MVC ViewModel member overridden by my ActionResult parameter ? |
C# | I was discovering the IL code of a simple program : I build this code in Release mode and this IL code is generated : I figure out pretty much all the insructions except this : Now this insruction should push int.MaxValue * 2L onto the stack and then blt.s will compare it with i , if i is less than the value go back to... | long x = 0 ; for ( long i = 0 ; i < int.MaxValue * 2L ; i++ ) { x = i ; } Console.WriteLine ( x ) ; .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 28 ( 0x1c ) .maxstack 2 .locals init ( [ 0 ] int64 x , [ 1 ] int64 i ) IL_0000 : ldc.i4.0 IL_0001 : conv.i8 IL_0002 : ... | What is the meaning of -2 in this IL instruction ? |
C# | I have n't noticed this behaviour yet , maybe because i prefer query syntax in VB.NET and split the query and the execution-methods into different statements . If i try to compile following simple query : The compiler does n't like this because he expects no arguments for List.Count : `` Public Readonly Property Count ... | Dim wordList As List ( Of String ) = New List ( Of String ) Dim longWords As Int32 = wordList.Count ( Function ( word ) word.Length > 100 ) Dim wordSeq As IEnumerable ( Of String ) = New List ( Of String ) Dim longWords As Int32 = wordSeq.Count ( Function ( word ) word.Length > 100 ) List < String > wordList = new List... | Can not use Enumerable.Count with List , compiler assumes List.Count |
C# | I got an object of I need to bring this into a I have no idea how to do this with LINQ . | List < List < string > > List < string > | with LINQ , how to transfer a List < List < string > > to List < string > ? |
C# | This is the background to this question : BackgroundTake any integer n greater than 1 and apply the following algorithmIf n is odd then n = n × 3 + 1 else n = n / 2If n is equal to 1 then stop , otherwise go to step 1The following demonstrates what happens when using a starting n of 66 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Sequence1 { class Program { static void Main ( string [ ] args ) { int start = 1 ; int flag = 0 ; int value ; while ( true ) { int temp = ( start - 1 ) / 3 ; string sta = temp.ToString ( ) ... | A recursion related issue in c # |
C# | I am developing UWP application for remote device using VS17 . I suddenly got this message And I am stuck at this error for about week . I dont know what cause it . Last thing that I made was that I move GPIO routines to external library . After that , each build ends with this message.What I tried : Turn off antivirus... | Error The `` WireUpCoreRuntime '' task failed unexpectedly.System.InvalidOperationException : Sequence contains no elements at System.Linq.Enumerable.Single [ TSource ] ( IEnumerable ` 1 source ) at Microsoft.Build.Net.CoreRuntimeTask.WireUpCoreRuntime.InternalExecute ( ) at Microsoft.Build.Net.CoreRuntimeTask.WireUpCo... | The `` WireUpCoreRuntime '' task failed unexpectedly Visual studio 2017 |
C# | I am trying to add timeout to this code , but because I am new to this , I ca n't figure out , Also I want main thread to wait here until it timeout for 5 minutes or completes.EditOr can I use cancellation token with this , if yes then how : ( ? | Task.Factory.StartNew ( ( ) = > { Aspose.Words.Document doc = new Aspose.Words.Document ( inputFileName ) ; doc.Save ( Path.ChangeExtension ( inputFileName , `` .pdf '' ) ) ; } ) ; | How can I add timeout to this code |
C# | Basically , I 'm wondering if I should listen to ReSharper in this instance ... You 'd figure that comparing to characters one should use Char.Equals ( char ) since it avoids unboxing , but Resharper suggests using Object.Equals ( obj ) . Maybe I 'm missing something here ? I 'm guessing it 's because there is a Depend... | private const DEFAULT_CHAR = ' # ' ; // DependencyProperty backingpublic Char SpecialChar { get { return ( Char ) GetValue ( SpecialCharProperty ) ; } } // ReSharper - Access to a static member of a type via a derived type.if ( Char.Equals ( control.SpecialChar , DEFAULT_CHAR ) ) { ... } | Char.Equals vs Object.Equals -- ReSharper suggests that I should use Object.Equals . Should I ? |
C# | I am trying to get the week number from a date time and in my case , the first day of the week is Monday and I want to follow the FirstFourDays convention.To check the results , I am checking this webpage : https : //espanol.epochconverter.com/semanas/2020To get the week number , I using the method : So I am trying to ... | System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear ( ) ; System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear ( new DateTime ( 2019 , 12 , 29 ) , System.Globalization.CalendarWeekRule.FirstFourDayWeek , DayOfWeek.Monday ) ; | Get the week number from a date time |
C# | I have an application that stores some data in firebird database . I 'm using an embedded firebird server and EntityFramework and all works greatfully but when I close my app by x button on form I get a windows system message `` application has stopped working '' and I ca n't catch this exception . I have an UnhandledE... | // Add handler for UI thread exceptionsApplication.ThreadException += new ThreadExceptionEventHandler ( UIThreadException ) ; // Force all WinForms errors to go through handlerApplication.SetUnhandledExceptionMode ( UnhandledExceptionMode.CatchException ) ; //This handler is for catching non-UI thread exceptions AppDom... | Embedded server application has stopped working after exit |
C# | Consider : In that case , the where clause is enforcing a specification that MyClass is only a generic of a reference type.Ideally I should have a unit test that tests this specification . However , this unit test obviously wo n't work , but it explains what I 'm trying to accomplish : What can I do to test a spec that... | class MyClass < T > where T : class { } [ Test ] [ DoesNotCompile ( ) ] public void T_must_be_a_reference_type ( ) { var test = new MyClass < int > ( ) ; } class MyClass < T > { } | How to write a unit test for `` T must be a reference type '' ? |
C# | Currently I 'm trying to understand dependency injection better and I 'm using asp.net MVC to work with it . You might see some other related questions from me ; ) Alright , I 'll start with an example controller ( of an example Contacts Manager asp.net MVC application ) Allright , awesome that 's working . My actions ... | public class ContactsController { ContactsManagerDb _db ; public ContactsController ( ) { _db = ContactsManagerDb ( ) ; } // ... Actions here } public class ContactsController { IContactsManagerDb _db ; public ContactsController ( ) { _db = ContactsManagerDb ( ) ; } public ContactsController ( IContactsManagerDb db ) {... | Dependency Injection what´s the big improvement ? |
C# | Here we are on EF Core and got 3 tables : NewsItemsLinksAnd more ( except News , Items ) : Content , Post , Form , etc.And my model definitionsTable Links describe URL for every News and every Item.This means that Links has 4 columns : IdType - news or itemRowId - contains ID of Item or News ( depends on the Type ) URL... | public class Item { public int Id { get ; set ; } public string Name { get ; set ; } public decimal Price { get ; set ; } public Link Link { get ; set ; } } public class News { public int Id { get ; set ; } public string Header { get ; set ; } public string Content { get ; set ; } public Link Link { get ; set ; } } pub... | How to setup entity relations in Entity Framework Core |
C# | I was reading an article on Linq to Sql and came across this : The author then translated the results in plain sql : And I thought to myself , `` holy cow ! would n't it be great if there was an extension to IQueryable that would generate these strings for you when debugging ? `` Anyone ever heard of anything like this... | IQueryProvider provider = new QueryProvider ( database.GetCommand , database.ExecuteQuery ) ; IQueryable < Product > source = new Queryable < Product > ( provider , database.GetTable < Product > ( ) ) ; IQueryable < string > results = source.Where ( product = > product.CategoryID == 2 ) .OrderBy ( product = > product.P... | Is there an api or extension to translate IQueryable < T > lambda expressions to SQL strings ? |
C# | I have this scenario : I have these classes : class A has collection of class B and class Ci have one class B and different base classes.when in class A collection there is only B that Ci not reference it , I can delete class A and all the B collection also deleted ( cascade delete ) . But when in class A collection th... | public class A { public int Id { get ; set ; } public virtual ICollection < B > bCollection { get ; set ; } } public class B { public int Id { get ; set ; } } public class C1 : BaseClass1 { public int Id { get ; set ; } public virtual B B { get ; set ; } } public class C2 : BaseClass2 { public int Id { get ; set ; } pu... | Ef code first complicate cascade delete scenario |
C# | I have 2 tables which have many-to-many relation.Code of entitiesI map this classes as many-to-many in the conform mapping.In xml this mapping compiles into this : The issue is that I can get categories from product entity , but when I try get products from category it 's does n't work and the list is empty . | public class Product : BaseEntity { public virtual string Name { get ; set ; } public virtual IList < Category > ProductCategory { get ; set ; } public virtual float Price { get ; set ; } public virtual string Description { get ; set ; } public virtual DateTime DateOfAdd { get ; set ; } public virtual float Discount { ... | NHibernate relationship has an issue with two-directional getting data |
C# | I have seen some code for working with AD in this stackoverflow questionI am getting confused about the using statement . I thought that it was just used for things that you are worried could become memory leak , like a WebClient , or similar ... Anyway : when I reach the line var groups = user.GetAuthorizationGroups (... | using ( var context = new PrincipalContext ( ContextType.Domain ) ) { using ( var user = UserPrincipal.FindByIdentity ( context , `` username '' ) ) { var groups = user.GetAuthorizationGroups ( ) ; ... } } | Confused with C # 'using ' |
C# | What is the meaning of `` new ( ) '' at the end of the above code ? | public interface ICrudService < T > where T : Entity , new ( ) | C # code confusion of where clause |
C# | I want to write c # code to make a snapshot-backup if available . This is supported since SQL Server version 2005 but only in Enterprise edition but not in Express or Standard edition . My question : how to find out in C # if the connected server supports snapshot backup ( is Enterprise Edition 2005 or newer or some ki... | sqlCommand.CommandText = String.Format ( `` CREATE DATABASE { 0 } ON `` + ( NAME = { 1 } , FILENAME = \ '' { 2 } \ '' ) AS SNAPSHOT OF { 1 } '' , databaseBackupName , databaseName , filenameOfDatabseBackup ) ; sqlCommand.ExecuteNonQuery ( ) ; | Find out in C # if my SQL Server instance supports snapshots ? |
C# | I use this code for drawing text in a panel : So I want to know what size the input text will be when rendered in the panel . | Graphics g = panel1.CreateGraphics ( ) ; g.DrawString ( ... ) ; | Graphics in C # ( .NET ) |
C# | We inherited a somewhat poorly-designed WCF service that we want to improve . One problem with it is that it has over a hundred methods ( on two different interfaces ) , most of which we suspect are not used . We decided to put some logging on each of the methods to track when and how they 're called . To make the trac... | public void LogUsage ( ) { try { MethodBase callingMethod = new StackTrace ( ) .GetFrame ( 1 ) .GetMethod ( ) ; string interfaceName = callingMethod.DeclaringType.GetInterfaces ( ) [ 0 ] .Name ; _loggingDao.LogUsage ( interfaceName , callingMethod.Name , GetClientAddress ( ) , GetCallingUrl ( ) ) ; } catch ( Exception ... | Why does Type.GetInterfaces ( ) sometimes not return a valid list ? |
C# | I am looking at the code from herewhat does param in param = > this.OnRequestClose ( ) refer to ? | /// < summary > /// Returns the command that , when invoked , attempts/// to remove this workspace from the user interface./// < /summary > public ICommand CloseCommand { get { if ( _closeCommand == null ) _closeCommand = new RelayCommand ( param = > this.OnRequestClose ( ) ) ; return _closeCommand ; } } | C # /Lambda : What does param in the following refer to ? |
C# | I have 2 sets of 2 classes where each pair has a super/sub-class relationship , and the orthogonal pair has a dependency relationship . What I am trying to determine is what to do with the constructors and/or bodies of the properties to keep the model as simple as possible with minimal data duplication.Here 's the stru... | public class Base1 { public List < Base2 > MyBase2Things { get ; set ; } // Do things with Base2 objects } public class Sub1 : Base1 { public List < Sub2 > MySub2Things { get ; set ; } // Do things with Sub2 objects and also with Base2 objects } public class Base2 { public Base1 MyBase1 { get ; set ; } // Do things wit... | How can I cleanly design a parallel inheritance structure in C # ? |
C# | I have a very basic Web API example that I constructed using the example code from this tutorial : CodeRelevant Web.config SectionRoute ConfigurationView ModelApiControllerand it 's leveraging ITSurveyEntities , which was a generated ADO.NET Entity Data Model from the database , which only contains a single table right... | < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < handlers > < remove name= '' ExtensionlessUrlHandler-ISAPI-4.0_32bit '' / > < remove name= '' ExtensionlessUrlHandler-ISAPI-4.0_64bit '' / > < remove name= '' ExtensionlessUrlHandler-Integrated-4.0 '' / > < add name= '' Extensionle... | Why is the response from my Web API not formed properly ? |
C# | I 'm working on a Fluent Api for a service which is fairly configurable , and just trying to work my options for a neat solution for the following problem.I have a class something like thisAll well and good , However can any one think of a way to achieve the following without having to verbosely specify the second gene... | public class WindowVm : DialogResultBase < MyReturnType > public IDialogWithResult < TViewModel , TSomeReturnType > DialogWithResult < TViewModel , TSomeReturnType > ( object owner = null ) where TViewModel : DialogResultBase < TSomeReturnType > .DialogWithResult < WindowVm > ( ) .DialogWithResult < WindowVm , ResultTy... | Generic type inference , Fluent Api , with pre-declared types |
C# | I have code like the following : Is there any way to avoid doing two lookups in the Dictionary -- the first time to see if contains an entry , and the second time to update the value ? There may even be two hash lookups on line ' B ' -- one to get the int value and another to update it . | class MyClass { string Name ; int NewInfo ; } List < MyClass > newInfo = ... . // initialize list with some valuesDictionary < string , int > myDict = ... . // initialize dictionary with some valuesforeach ( var item in newInfo ) { if ( myDict.ContainsKey ( item.Name ) ) // ' A ' I hash the first time here myDict [ ite... | Do I have to hash twice in C # ? |
C# | Count-based filtering without a time constraintHow to introduce inactivity reset ? But how to introduce a timeout TimeSpan tooLong so that the counting would restart from zero whenever the interval between two values exceeds this maximum ? | IObservable filteredStream = changes.Buffer ( 3 ) ; | reset count above max time interval , in Rx count-based aggregation |
C# | I was looking to write a simple desktop app and a corresponding mobile app , the scenario would be : I run the desktop app on my laptopI run the mobile app on my Lumia ( on the same wifi network ) The phone app somehow finds and connects to the desktop app ( I do n't want to have to manually find and type the ip ) The ... | UdpClient udp = new UdpClient ( port ) ; IPAddress group_ip = IPAddress.Parse ( `` 139.100.100.100 '' ) ; IPEndPoint client_ipep = new IPEndPoint ( group_ip , 3344 ) ; byte [ ] b = System.Text.Encoding.UTF8.GetBytes ( txtEntry.Text ) ; udp.Send ( b , b.Length , client_ipep ) ; HostName hostName = new HostName ( `` 139.... | Network Service Discovery on Windows Phone |
C# | A co-worker showed me a very strange behavior and I 'd like to know if someone could explain me why.A basic constructor with 2 string params : Method is : When this ctor is called within an aspx page with str2 as null , all works fine because if an operand of string concatenation + is null , an empty string is substitu... | public MyClass ( string str1 , string str2 ) { this.s1 = str1 ; this.s2 = str2 ; this.s3 = Method ( str2 + `` ._className '' , str1 ) ; } public string Method ( string key , string defaultValue ) { List < string > list = _vars [ key ] ; if ( list == null ) return defaultValue ; string res = `` '' ; foreach ( string s i... | + string concat operator with a null operand |
C# | I 've got some code I 'm maintaining that has a good deal of machine generated comments and machine generated regions . ( or created by a particularly misled developer ) These are comments exclusively repeating the method metadata and space expansions of pascal cased names : Is there a plug in or feature of Resharper f... | # region methods/// < summary > /// Implementation of a public method foo bar , returning a void/// < /summary > /// < param name= '' value '' > A string parameter named value input < /param > public void fooBar ( string valueInput ) { } # endregion | How to strip out robo-comments and # region from C # ? |
C# | I have two string lists which have same size.I want to create a dictionary , the key is from listA , the value is from listB.What is the fast way ? I used the code : I do n't like this way , can I use ToDictionary method ? | List < string > ListA ; List < string > ListB ; Dictionary < string , string > dict = new Dictionary < string , string > ( ) ; for ( int i=0 ; i < ListA.Count ; i++ ) { dict [ key ] = listA [ i ] ; dict [ value ] = listB [ i ] ; } | Use ToDictionary to create a dictionary |
C# | I have a search page which contains two search result types : summary result and concrete result.Summary result page contains top 3 result per category ( top hits ) Concrete result page contains all result for a selected category.To obtain the Summary page I use the request : And I get result , for exampleSo i get few ... | var searchDescriptor = new SearchDescriptor < ElasticType > ( ) ; searchDescriptor.Index ( `` index_name '' ) .Query ( q = > q.MultiMatch ( m = > m .Fields ( fs = > fs .Field ( f = > f.Content1 , 3 ) .Field ( f = > f.Content2 , 2 ) .Field ( f = > f.Content3 , 1 ) ) .Fuzziness ( Fuzziness.EditDistance ( 1 ) ) .Query ( q... | ElasticSearch - different result ordering for simple request and aggregation request ( NEST ) |
C# | I have a program that processes high volumes of data , and can cache much of it for reuse with subsequent records in memory . The more I cache , the faster it works . But if I cache too much , boom , start over , and that takes a lot longer ! I have n't been too successful trying to do anything after the exception occu... | Loop Dim memFailPoint As MemoryFailPoint = Nothing Try memFailPoint = New MemoryFailPoint ( mysize ) `` // size of MB of several objects I 'm about to add to cache memFailPoint.Dispose ( ) Catch ex As InsufficientMemoryException `` // dump the oldest items here End Try `` // do worknext loop . | How do I know if I 'm about to get an OutOfMemoryException ? |
C# | While I try to run following code snippet , it ’ s executing wrong overload method . I 'm confused why it does that ? [ testB.TestMethod ( testValue ) method execute the public double TestMethod ( double value ) method ] Do you have any idea about this ? Is there are any way to call TestA class method via the TestB ins... | public class TestA { public int TestMethod ( int value ) { return value ; } } public class TestB : TestA { public double TestMethod ( double value ) { return value ; } } static void Main ( string [ ] args ) { TestB testB = new TestB ( ) ; int testValue = 3 ; testB.TestMethod ( testValue ) ; } | Why does the compiler cast automatically without going further in the inheritance ? |
C# | I have made a server and a client in C # which transfers files . But when transferring it pauses for some seconds and then continues . I have uploaded a video on YouTube to demonstrate : http : //www.youtube.com/watch ? v=GGRKRW6ihLoAs you can see it sometime pauses and then continues.Receiver : Sender : | using ( var writer = new StreamWriter ( Path.Combine ( _localPath , file.FileName ) ) ) { var buffer = new byte [ _bufferSize ] ; while ( file.Transferred < file.Size & & _active ) { int read = ns.Read ( buffer , 0 , _bufferSize ) ; writer.BaseStream.Write ( buffer , 0 , read ) ; file.Transferred += read ; } writer.Clo... | Network transfer pauses |
C# | Extension methods with . operator always called , even if object is null without throwing NullReferenceException . By using operator ? . it will never called . For example : Why extension method is n't called in this case ? Is this an ambiguos feature ? | using System ; public class Program { public static void Main ( ) { A a = null ; a.b ( ) ; // works a ? .b ( ) ; // does n't work } } public class A { } public static class ext { public static void b ( this A a ) { Console.WriteLine ( `` I 'm called '' ) ; } } | Operator ? . and extension methods |
C# | I have a class like this : Somewhere else I 'm using it : I thought it will returns S , but it throw exception . Any idea what is going on ? | class MyClass { public object [ ] Values ; } MyClass myInstance = new MyClass ( ) { Values = new object [ ] { `` S '' , 5 , true } } ; List < Func < MyClass , object > > maps = new List < Func < MyClass , object > > ( ) ; for ( int i = 0 ; i < myInstance.Values.Length ; i++ ) { maps.Add ( obj = > obj.Values [ i ] ) ; }... | Index was outside the bounds of array when using List < Func < T , object > > |
C# | Okay , this is probably very simple but , I have the below `` checks '' ( not at the same time ) and the First ALWAYS evaluates to TRUE while the Second SEEMS to work . This actually happens in each place that the row value is a number or bool ( Date seems fine ... ) . If I walk through the code in Debug it shows the v... | if ( row [ `` PersonID '' ] ! = tbxPersonID.EditValue ) { row [ `` PersonID '' ] = tbxPersonID.EditValue ; } if ( row [ `` CitizenFlag '' ] ! = chkCitizen.EditValue ) { row [ `` CitizenFlag '' ] = chkCitizen.EditValue ; _whatChanged.Add ( `` CitizenFlag '' ) ; } if ( row [ `` PersonID '' ] .ToString ( ) ! = tbxPersonID... | Comparing expressions of type object |
C# | How do I enable allowed services : WINDOWS AZURE SERVICES as seen in the Management Portal in c # ? | _client = new SqlManagementClient ( GetSubscriptionCredentials ( ) ) ; var result = _client.Servers.CreateAsync ( new ServerCreateParameters { AdministratorUserName = _config.ServerUserName , AdministratorPassword = _config.ServerPassword , Location = _config.Location , Version = `` 12.0 '' } , CancellationToken.None )... | How do enable internal Azure Services for SQL Azure in c # |
C# | Given that I have three tables ( Customer , Orders , and OrderLines ) in a Linq To Sql model where Customer -- One to Many - > Orders -- One to Many - > OrderLinesWhen I useI see one query getting the customer , that makes sense . Then I see a query for the customer 's orders and then a single query for each order gett... | var customer = Customers.First ( ) ; var manyWay = from o in customer.CustomerOrders from l in o.OrderLines select l ; var tableWay = from o in Orders from l in OrderLines where o.Customer == customer & & l.Order == o select l ; | How can I make this SelectMany use a Join ? |
C# | When I use a foreach loop in C # , it appears that no compile time type checking is performed if the item type is an interface type.E.g.This will happily compile and cause an exception at runtime , when it is clear at compile time this makes no sense . If I change the item type from SomeInterface to another class , the... | class SomeClass { } interface SomeInterface { } IEnumerable < SomeClass > stuff ; foreach ( SomeInterface obj in stuff ) { // This compiles - why ! ? } IEnumerable < SomeClass > stuff ; foreach ( Random obj in stuff ) { // This does n't compile - good ! } | Why does foreach skip compile time type checking on interface types ? |
C# | Consider this code in a project : This works like a charm . However , as soon as you separate these two functions into two different projects , the code breaks : The error I get in the second case is : object ' does not contain a definition for 'Name ' ( RuntimeBinderException ) Why do I get this error ? What 's the al... | static void Main ( string [ ] args ) { DoSomething ( new { Name = `` Saeed '' } ) ; } public static void DoSomething ( dynamic parameters ) { Console.WriteLine ( parameters.Name ) ; } // This code is in a Console Applicationstatic void Main ( string [ ] args ) { ExternalClass.DoSomething ( new { Name = `` Saeed '' } ) ... | Why this dynamic parameter is not working ? |
C# | I ’ m making a bot that can test some card tactics on a game , the bot works but I have one problem . My card shake method is not very good . I shake the cards this way : The problem is when I calculate without a pause between the card shake process , a few players will win a lot of games . For exampleBut when I add a ... | public void ShuffelDeck ( ) { for ( int i = 0 ; i < 5 ; i++ ) Cards = ShuffelCards ( Cards ) ; } private ArrayList ShuffelCards ( ArrayList Cards ) { ArrayList ShuffedCards = new ArrayList ( ) ; Random SeedCreator = new Random ( ) ; Random RandomNumberCreator = new Random ( SeedCreator.Next ( ) ) ; while ( Cards.Count ... | Brute force Card shake method in C # |
C# | I would like to be able to generate a ( pseudo ) random number from n possible ranges , where a range is x , y and x < y . For example , executing this code : will produce something like : The signature of the method NextRanges is : And Range is defined as : The only thing I 'm not sure on is how to implement NextRange... | for ( int i = 0 ; i < 10 ; i++ ) { Console.Write ( Random.NextRanges ( new Range ( 1 , 6 ) , new Range ( 10 , 16 ) , new Range ( 20 , 31 ) ) + `` `` ) ; } 3 12 5 22 1 27 29 5 10 24 public static int NextRanges ( params Range [ ] ranges ) public struct Range { public int X ; public int Y ; public Range ( int x , int y )... | How can I get a single random number from multiple possible ranges ? |
C# | I have two methods like this : I want to extract the Write ( ) and Clear ( ) methods to a new method ( Action ) to have something like this : The Write ( ) and Clear ( ) will be defined in Execute ( ) just one time.What 's the right syntax to do so ? | public void ExecuteA ( ) { Write ( ) ; // A specific work Clear ( ) ; } public void ExecuteB ( ) { Write ( ) ; // B specific work Clear ( ) ; } public ASpecificWork ( ) { // do A work } public BSpecificWork ( ) { // do B work } Execute ( BSpecificWork ) ; Execute ( ASpecificWork ) ; | C # Action syntax |
C# | I 'm a pretty big newbie when it comes to optimization . In the current game I 'm working on I 've managed to optimize a function and shave about 0.5 % of its CPU load and that 's about as 'awesome ' as I 've been.My situation is as follows : I 've developed a physics heavy game in MonoTouch using an XNA wrapper librar... | return new Vector2 ( Max ( v1.x , v2.x ) , Max ( v1.y , v2.y ) ) | Optimization of a GC language , any ideas ? |
C# | Suppose I writeThe sequence produced is 1 1 2 1 2 3 as expected . But now if I writeNow the sequence produced is 1 1 2 1 2 1 3 2 3 4 instead of what one would expect 1 1 2 1 2 3 1 2 3 4 . Why is that ? Does SelectMany ( ) do some kind of multithreaded merge ? | var gen = Observable.Range ( 1 , 3 ) .SelectMany ( x = > Observable.Range ( 1 , x ) ) ; var gen = Observable.Range ( 1 , 4 ) .SelectMany ( x = > Observable.Range ( 1 , x ) ) ; | Why are these Rx sequences out of order ? |
C# | I 've run into an issue with stringbuilder which I ca n't seem to solve . To simplify the problem I create the following method : It should just add that line 1500 times , and afterwards combine it to a string and return it . However instead of just combining it corrupts the content . Somewhere in the middle of the res... | private static string TestBigStrings ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 1 ; i < 1500 ; i++ ) { string line = `` This is a line is n't too big but breaks when we add to many of it . `` ; builder.AppendLine ( line ) ; } return builder.ToString ( ) ; } This is a line is n't too big but bre... | C # Stringbuilder corrupting content when adding lots of text |
C# | I have a small WPF application which has a window with an Image control . Image control shows an image from File system . I want user to be able to drag the image and drop to its desktop or anywhere to save it . It 's working fine.But I want to show small image thumbnail along with mouse cursor when user drags it . Jus... | < Grid > < Image x : Name= '' img '' Height= '' 100 '' Width= '' 100 '' Margin= '' 100,30,0,0 '' / > < /Grid > public partial class MainWindow : Window { string imgPath ; Point start ; bool dragStart = false ; public MainWindow ( ) { InitializeComponent ( ) ; imgPath = `` C : \\Pictures\\flower.jpg '' ; ImageSource ima... | Showing Image thumbnail with mouse cursor while dragging |
C# | In static OOP languages , interfaces are used in order to declare that several classes share some logical property - they are disposable , they can be compared to an int , they can be serialized , etc.Let 's say .net did n't have a standard IDisposable interface , and I 've just came up with this beautiful idea : My ap... | interface IDiscardable { void Discard ( ) ; } | Is there any advantage in disallowing interface implementation for existing classes ? |
C# | I have a litte problem on Console.WriteLine ( ) . I have my while ( true ) loop that would check the data if exist and it would allow checking the data 3 times . And inside my loop I have this message : Console.WriteLine ( string.format ( `` Checking data { 0 } '' , ctr ) ) ; Here 's my sample code below : Let 's assum... | int ctr = 0 ; while ( true ) { ctr += 1 ; Console.WriteLine ( string.format ( `` Checking data { 0 } ... '' , ctr ) ) if ( File.Exist ( fileName ) ) break ; if ( ctr > 3 ) break ; } Checking data 1 ... Checking data 2 ... Checking data 3 ... Checking data 1 ... 2 ... 3 ... | Problems with console output in C # |
C# | I 'm using Swashbuckle.AspNetCore ( 4.0.1 ) to generate a simple SwaggerUI for testing like it 's described here . My ApiController have two routes : The SwaggerUI displays all controller endpoints two times ( one with systemId , one without systemId ) . This is good , but the problem is , when I click on e.g /api/valu... | [ Route ( `` api/values '' ) ] [ Route ( `` api/ { systemId } /values '' ) ] | .NET Core API : Disable multiple route expanding in SwaggerUI |
C# | In the C # specification ( 17.2 ) it indicates there are several attribute targets when specifying an attribute . This is common when you need to apply an attribute to something that does n't often have a `` real '' place to specify an attribute . For example , the return target is used often in platform Invoke : Howev... | [ return : MarshalAs ( UnmanagedType.Bool ) ] static extern bool SomeWin32Method ( ) ; //Assume this is valid , has a DllImport , etc . [ method : DllImport ( `` somelib.dll '' ) ] static extern bool SomeWin32Method ( ) ; | What is the purpose of the method attribute-target ? |
C# | I have the following piece of reduced CIL code.When this CIL method is executed , an InvalidProgramException is being thrown by the CLR : My question is , why is this CIL code invalid ? Several obervations : - If localloc is removed , the code runs fine . To my knowledge , localloc replaces the parameter size on the st... | .method assembly hidebysig specialname rtspecialname instance void .ctor ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < class System.Windows.Input.StylusDeviceBase > styluses ) cil managed { .locals init ( class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < class System.Windows.Input.Styl... | Why does localloc break this CIL method ? |
C# | I have a Windows service that every 5 seconds checks for work . It uses System.Threading.Timer for handling the check and processing and Monitor.TryEnter to make sure only one thread is checking for work . Just assume it has to be this way as the following code is part of 8 other workers that are created by the service... | readonly object _workCheckLocker = new object ( ) ; public Timer PollingTimer { get ; private set ; } void InitializeTimer ( ) { if ( PollingTimer == null ) PollingTimer = new Timer ( PollingTimerCallback , null , 0 , 5000 ) ; else PollingTimer.Change ( 0 , 5000 ) ; Details.TimerIsRunning = true ; } void PollingTimerCa... | Monitor.TryEnter and Threading.Timer race condition |
C# | Assuming I have a list How can I use LINQ to obtain a list of lists as follows : So , i have to take the consecutive values and group them into lists . | var listOfInt = new List < int > { 1 , 2 , 3 , 4 , 7 , 8 , 12 , 13 , 14 } { { 1 , 2 , 3 , 4 } , { 7 , 8 } , { 12 , 13 , 14 } } | Split array with LINQ |
C# | How could I refactor the methodif I wished to avoid using the anonymous method here ? | private void ListenToPropertyChangedEvent ( INotifyPropertyChanged source , string propertyName ) { source.PropertyChanged += ( o , e ) = > { if ( e.PropertyName == propertyName ) MyMagicMethod ( ) ; } ; } | How to avoid anonymous methods in `` dynamic '' event subscription ? |
C# | Consider this small program . Ignore , if you will , the generic catch , I 've kept it brief to try and illustrate the point : When run , the following ( with some of the path info removed ) is produced : My question is - why does the stack trace of the exception stop unwinding the method chain at the Try ( ) method ? ... | private static void Main ( string [ ] args ) { Try ( Fail ) ; } private static void Fail ( ) { var x = ( ( string ) null ) .Clone ( ) ; } private static void Try ( Action action ) { try { action ( ) ; } catch ( Exception exc ) { Debug.WriteLine ( exc.StackTrace ) ; } } at Scratch.Program.Fail ( ) in Program.cs : line 2... | Why does catch in a method handling an Action truncate the stack trace ? |
C# | This is probably not possible , but here goes : I want to create a struct where I can define the amount of arguments at declaration.for example , now I am using : but KeyValuePair can only ever take a Key , and a Value .Is it possible to make something like : I think this is n't possible , but maybe I just do n't know ... | KeyValuePair < T , T > CustomValues < T , { T , { .. } } > | Variable length arguments c # |
C# | VS now comes with an interactive window , but unlike running the raw CSI.EXE Roslyn process , Visual Studio adds IntelliSense and a few other features such as being able to load in the current project.I want to write a VS plug-in that tracks all text editor changes in this window . Is this possible ? What I 'm looking ... | var dte = Shell.Instance.GetComponent < DTE > ( ) ; foreach ( Window window in dte.MainWindow.Collection ) { if ( window.Kind.ToUpper ( ) .Contains ( `` TOOL '' ) ) { if ( window.Caption == `` C # Interactive '' ) { WpfWindow wpfWindow = ( WpfWindow ) HwndSource.FromHwnd ( ( IntPtr ) window.HWnd ) .RootVisual ; for ( i... | Tracking changes in C # interactive window |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.