lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | When I run this snippet of code : I get this SQL : Note that @ p0 and @ p1 are both bar , when I wanted them to be foo and bar . I guess Linq is somehow binding a reference to the variable word rather than a reference to the string currently referenced by word ? What is the best way to avoid this problem ? ( Also , if ... | string [ ] words = new string [ ] { `` foo '' , `` bar '' } ; var results = from row in Assets select row ; foreach ( string word in words ) { results = results.Where ( row = > row.Name.Contains ( word ) ) ; } -- Region ParametersDECLARE @ p0 VarChar ( 5 ) = ' % bar % 'DECLARE @ p1 VarChar ( 5 ) = ' % bar % ' -- EndReg... | Why are my bound parameters all identical ( using Linq ) ? |
C# | I come from the Wild Wild West of PHP and Javascript where you can return anything from a function . While I do hate that lack of accountability , I also face a new challenge in my effort to keep my code `` perfect '' . I made this generic function to pick a random element from a listBut I want to protect myself from u... | public static T PickRandom < T > ( this IList < T > list ) { Random random = new Random ( ) ; int rnd = random.Next ( list.Count ) ; return list [ rnd ] ; } if ( myList.Count > 0 ) foo = Utilites.PickRandom ( myList ) ; | Avoiding out of range issues in generic functions |
C# | I am learning about the ins-and-outs of nullable reference types in C # 8.0Whilst reading this blog about nullable reference types , I was left a bit puzzled by the following example.The author shows how a [ DisallowNull ] attribute can be used in this case . However , my query is why would you need the attribute here ... | public static HandleMethods { public static void DisposeAndClear ( [ DisallowNull ] ref MyHandle ? handle ) { ... } } public static HandleMethods { public static void DisposeAndClear ( ref MyHandle handle ) { ... } } public static void DisposeAndClear ( [ DisallowNull ] ref MyHandle ? handle ) { handle = null ; } | Using [ DisallowNull ] vs non-nullable reference type |
C# | The following code fragmentthrows this ( expected as the path is invalid ) exception when run with .Net 4.6.2System.NotSupportedException : 'The given path 's format is not supported . 'But when I run the same code with .Net Core 3.2.1 , the method simply returns the input without throwing an exception . AFAIKT the doc... | var x = Path.GetFullPath ( @ '' C : \test : '' ) ; | GetFullPath behavior in .Net Core 3.1.2 differs from .Net 4.6.1 |
C# | Using C # regex to match and return data parsed from a string is returning unreliable results.The pattern I am using is as follows : Following are a couple test cases that failShould returnShow Name ( eg , Ellen ) Date ( eg , 2015.05.22 ) Extra Info ( eg , Joseph Gordon Levitt [ REPOST ] ) Should returnShow Name ( eg ,... | Regex r=new Regex ( @ '' ( .* ? ) S ? ( \d { 1,2 } ) E ? ( \d { 1,2 } ) ( .* ) | ( .* ? ) S ? ( \d { 1,2 } ) E ? ( \d { 1,2 } ) '' , RegexOptions.IgnoreCase ) ; Ellen 2015.05.22 Joseph Gordon Levitt [ REPOST ] The Soup 2015.05.22 [ mp4 ] Big Brother UK Live From The House ( May 22 , 2015 ) Alaskan Bush People S02 Wild ... | Regex pattern is n't matching certain show titles |
C# | I have the following code in C # : and the output isSystem.Action ? ? ? while if you add an int instead of a string to d it would throw an exception.Can you please explain why does this happen ? | Action a = new Action ( ( ) = > Console.WriteLine ( ) ) ; dynamic d = a ; d += `` ? ? ? `` ; Console.WriteLine ( d ) ; | concatenating an action with a string using dynamics |
C# | I 'm trying to build a regex in C # that has the following characteristics.The string starts with zero or more numbersFollowed by the letters `` ABC '' Followed by the end of the stringI 've triedbut still matches things like ZABC , ABCD , 2ZABC.any pointers ? | \d ? ABC | C # regular expression ignores extra data at ends |
C# | First off , sorry it this is n't written very well , I 've spend hours debugging this and I 'm very stressed . I 'm trying to make a moving platform in unity that can move between way-points , I do n't want to have to have tons of gameobjects in the world taking up valuable processing power though so I 'm trying to use... | public Vector3 [ ] localWaypoints ; Vector3 [ ] globalWaypoints ; public float speed ; public bool cyclic ; public float waitTime ; [ Range ( 0 , 2 ) ] public float easeAmount ; int fromWaypointIndex ; float percentBetweenWaypoints ; float nextMoveTime ; void Start ( ) { globalWaypoints = new Vector3 [ localWaypoints.L... | Strange outputs for a moving platform in Unity |
C# | In c # any type that implements comparison operators like < > , can easily be compared . For example I can do this : However , i 'm not able to do the following this does n't compile , since the first comparison returns a boolean , which is n't further compareable to other datesSo I have to do it like this instead ( Da... | var date1 = new DateTime ( 1000 ) ; var date2 = new DateTime ( 2000 ) ; var date3 = new DateTime ( 3000 ) ; var result = date1 < date2 ; // true var result = date1 < date2 < date3 ; // error var result = date1.CompareTo ( date2 ) + date2.CompareTo ( date3 ) == -2 ; // true var result = date1 < date2 & & date2 < date3 ;... | Is there an easy way to stack Comparison operators in c # ? |
C# | I have a control which shows a list of all PDFs in a selected folder . The names of most of these PDFs ( for example , meeting minutes ) begin with a date . I want these PDFs shown in descending order so that the most recent PDFs are shown at the top.In the same folder I also have some PDFs whose names do not contain a... | private void GenerateFolder ( ) { folder_path = Server.MapPath ( BaseFolder ) ; _folder_view = new StringBuilder ( ) ; if ( Directory.Exists ( folder_path ) ) { DirectoryInfo info = new DirectoryInfo ( folder_path ) ; FileInfo [ ] files = info.GetFiles ( ) .OrderByDescending ( p = > p.FullName ) .ToArray ( ) ; foreach ... | Sort part of a list in descending order ( by date ) , the other part in ascending order ( alphabetically ) ? |
C# | The following operator overload is defined inside my Term class : This class also defines an implicit conversion from a Variable to Term : I would like to understand why the following does not compile : The compiler says : Operator '* ' can not be applied to operands of type 'int ' and 'OOSnake.Variable'Why is n't my o... | public static Term operator * ( int c , Term t ) { ... } public static implicit operator Term ( Variable var ) { ... } static void Main ( string [ ] args ) { Variable var = ... ; // the details do n't matter Console.WriteLine ( 2 * var ) ; // var is n't implicitly converted to Term ... Console.ReadKey ( ) ; } namespace... | User-defined implicit conversion of overloaded operator 's arguments |
C# | I have a enum , with members that are same value , but when I tried to print them as strings , I expected to see it uses the first defined value , that is , for Buy and Bid it prints Buy , and for Sell and Ask it prints Sell , but the test shows it looks they are randomly chosen , as it is neither first nor last for al... | using System ; public enum OrderType { Buy , Bid = Buy , Sell , Ask = Sell } public class Program { public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; OrderType o = OrderType.Buy ; Console.WriteLine ( `` { 0 } : { 1 } '' , ( int ) o , o ) ; OrderType o2 = OrderType.Bid ; Console.WriteLine ( `` { 0 ... | Why is Enum string value inconsistent ? |
C# | Assume I have a C # method like this : ( obviously not real code ) As you can guess by the naming , the objects that are returned by these methods are gigantic . Hundreds of megabytes total RAM required by each , although the first two objects are composed of millions of smaller objects instead of one huge chunk like t... | byte [ ] foo ( ) { var a = MethodThatReturns500mbObject ( ) ; var b = MethodThatReturns200mbObject ( a ) ; byte [ ] c = MethodThatReturns150mbByteArray ( b ) ; byte [ ] d = UnwiselyCopyThatHugeArray ( c ) ; return d ; } | When are method local .NET objects eligible for GC ? |
C# | First thing first . I hope my title is not misleading . I tried my best to phrase it.Now , see the code below . Case 1 is pretty straight forward . Both cases work as expected . My question is why does compiler allow Case 2 ? Are there specific scenarios when this is desired . I can not think of one . | interface IEmployee { void Register ( string role ) ; } abstract class Employee : IEmployee { public void Register ( string role ) { Console.WriteLine ( role ) ; } } // Case 1class Manager : Employee { } // Case 2class Developer : Employee , IEmployee { } class Test { public void Test1 ( ) { IEmployee emp1 = new Manage... | Inherit Class1 and implement Interface1 both in case Class1 already implements Interface1 |
C# | I am not sure whether I 've framed the question properly above in subject but I will try to explain to my best about the question I have.I have below ContactUsModel which is a part of HomeViewModel , better say Nested Model Class in a single modeland I am getting this Model referred in HomeViewModel as below : Now in I... | public class ContactUsDataModel { public string ContactName { get ; set ; } public string ContactEmail { get ; set ; } public string ContactMessage { get ; set ; } public string ContactPhone { get ; set ; } } public class HomeViewModel { /*My other models goes here*/ public ContactUsDataModel CUDModel { get ; set ; } }... | Does model maintains its structure when data is received in controller ? |
C# | I know that when authorizing requests with OAuth , we can use several scopes to ask for a specific permission from the user . I want to ask for the permission for downloading files with publicly shared links ( the user will actually provide this link ) .However , the scopes listed here do not provide such an option . I... | private string [ ] Scopes = { DriveService.Scope.DriveFile } ; private DriveService GetDriveServiceInstance ( ) { UserCredential credential ; using ( var stream = new FileStream ( `` Services/credentials.json '' , FileMode.Open , FileAccess.Read ) ) { string credPath = `` token.json '' ; credential = GoogleWebAuthoriza... | Allowing to download a google doc only if the file is shared publicly |
C# | I have below text line and I intend to extract the `` date '' after the `` , '' , i , e , 1 Sep 2015Allocation/bundle report 10835.0000 Days report step 228 , 1 Sep 2015I wrote the below regex code and it returns empty in the match.Can you advice about what 's wrong with the Regex format that I mentioned ? | ` Regex regexdate = new Regex ( @ '' \Allocation/bundle\s+\report\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\ , \+ ( \S ) +\s+ ( \S ) +\s+ ( \S ) '' ) ; // to get datesMatchCollection matchesdate = regexdate.Matches ( text ) ; | Regex format returns empty result - C # |
C# | I have an entity list , where one of the fields ( UtcOffset ) is a number.And I have a filter list offsets which is a list of numbers.I want to select with a LINQ from the first list all the entities where the UtcOffset field is equal or less than to the values from the filter list with the fixed delta ( 3600 ) added.I... | public class TimeZone { public int Id { get ; set ; } public string Name { get ; set ; } public int UtcOffset { get ; set ; } } var delta = 3600 ; List < TimeZone > TimeZones = new List < TimeZone > ( ) { new TimeZone ( ) { Id = 1 , Name = `` America/Tortola '' , UtcOffset = -14400 } , new TimeZone ( ) { Id = 2 , Name ... | LINQ : Filter the list according to the math condition above elements in another list |
C# | I 'm writing an API with .NET Core 3.1 . This API has an asynchronous function called GetSomeProperty ( ) , which I use in an endpoint ( called Get ) .When receiving the response from this endpoint , the results properties are `` moved down '' one layer , and wrapped in metadata from the asynchronous method , like this... | `` results '' : [ { `` result '' : { //actual result here } `` id '' : 1 , `` status '' : 5 , `` isCanceled '' : false , `` isCompleted '' : true , `` creationOptions '' : 0 , `` isFaulted '' : false } , { `` result '' : { //actual result here } `` id '' : 2 , `` status '' : 5 , `` isCanceled '' : false , `` isComplete... | Asynchronous function returns async metadata ( including result ) instead of just result |
C# | I have the following format var format = `` 0\ '' '' ; I then use it like this 1.ToString ( format ) ; I 'm expecting it to return 1 '' but it returns 1How do I make it insert the double quote ( `` ) ? I have tried ... and ca n't get it to work.It does work if I use string.Format ... that will give me 1 '' as required ... | var format = `` 0\u0022 '' ; var format = @ '' 0 '' '' '' ; var format = `` { 0 } \ '' '' ; string.Format ( format , 1 ) | int.ToString ( format ) not inserting `` literal |
C# | I have my structure : If I put the structure in Program.cs or another File.cs , and I create a variable as MyType ( my structure ) and I try to use it , the result is an obvious error : CS0165 Use of unassigned local variableExample : The problem is when I put the structure in a class library ( either in another projec... | public struct MyType { private string value ; // Methods // ... ( ToString overrided too ) } MyType a ; Console.WriteLine ( a ) ; // Error : Use of unassigned local variable ' a'MyType b = new MyType ( ) ; Console.WriteLine ( b ) ; // Prints the default value ( an empty string ) MyType a ; Console.WriteLine ( a ) ; // ... | Class library allow use unassigned structures |
C# | I 'm trying to print `` x '' for the value within the array for example the integer 32 would print 32 x 's but I 'm not sure how to go about doing so.Any help or pointers on what to do would be great have looked around but ca n't seem to find anything that helps me without over complicating it . | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading ; using System.Threading.Tasks ; namespace Histogram { class Program { static void Main ( string [ ] args ) { string output = `` '' ; int [ ] x ; x = new int [ 18 ] ; int [ ] y = { 32 , 27 , 64 , 18 , 95 , 1... | Print X for value of Array |
C# | The real world example is quite simple . There is a house and the house has walls and so on.Now a developer has added the property room to the class wall a few years ago : It is very pleasant to have this object in the class . One has access to the parent element in many places ( 430 ) . But I think it does not belong ... | class Room { public List < Wall > Walls { get ; set ; } } class Wall { public List < WallObject > WallObjects { get ; set ; } } class Wall { public List < WallObject > WallObjects { get ; set ; } public Room Room { get ; set ; } } | Parent element in child class |
C# | I want to insist that I can call TryParse on T. Is it possible to restrict T in that way ? TryParse is not part of an interface , it just seems to exist on a number of value types , so how would I do this ? | public int DoSomething < T > ( string someString ) | How would I constrain a generic method in C # to only allow T where T has TryParse ? |
C# | This is my code : I 'd like to return the list of each record with a `` distinct '' obj.ID . How can I do this ? | objectList = ( from MyObject obj in MyObjects select r ) .ToList ( ) ; | How can I GroupBy this LINQ query ? |
C# | Look at the following LINQPad program : This compiles without a hitch . Why ? Specifically : Why do n't I have to write this : Is the attribute declaration deemed to be `` inside '' the type , and thus in scope ? | void Main ( ) { } [ TestAttribute ( Name ) ] public class Test { public const string Name = `` Test '' ; } [ AttributeUsage ( AttributeTargets.Class , AllowMultiple = false , Inherited = false ) ] [ Serializable ] public class TestAttribute : Attribute { public TestAttribute ( string dummy ) { } } [ TestAttribute ( Nam... | Why is this legal ? Referring to a constant in a type , from an attribute *on* the type , without prefixing with type name ? |
C# | I have the input strings as below1 ) ISBN_9781338034424_001_S_r1.mp32 ) 001_Ch001_987373737.mp33 ) This Is test 001 Chap01.mp34 ) Anger_Cha01_001.mp3and I am using below regex to pick `` 001 '' into TrackNumber groupHowever the above also picking up the `` 978 '' , `` 133 '' , `` 803 '' and etc into TrackNumber group (... | ( ? : ( ? < TrackNumber > \d { 3 } ) | ( ? < Revision > r\d { 1 } ) ) ( ? ! [ a-zA-Z ] ) | Pick the exact digit match from a string |
C# | In the above lambda , while calculating percentage for eg I want to write ( totresponcecount/Count ) *100 where Count is already calculated in above statement.So how can I access Count value to write Perc = ( totresponcecount/Count ) *100 ? | db.opt.Select ( z = > new { z.QuestionTitle , Count = z.Responces.Where ( x = > x.Responseval == Constants.options.Agree ) .Count ( ) , Perc = ( totresponcecount/Count ) *100 } ) .ToList ( ) ; | Reuse anonymous variable within select statement |
C# | In c # code , i found this implement . I tried to find out what this in and out meaning , but only explanation of out keyword in there . So what these in and out keyword do ? | public delegate Tb Reader < in Ta , out Tb > ( Ta a ) ; | What is in and out on delegate in c # ? |
C# | This answer to another question of mine did not compile , though on the surface it seems it should ( this is n't the same question , I can rewrite the other answer to work for my other question ) .Given Why is the compiler running into trouble with the null coalescent operator , but not with the syntax-sugar-free if/el... | private Func < MyT , bool > SegmentFilter { get ; set ; } public MyConstructor ( Func < MyT , bool > segmentFilter = null ) { // This does not compile // Type or namespace mas could not be found SegmentFilter = segmentFilter ? ? ( mas ) = > { return true ; } ; // This ( equivalent ? ) form compiles just fine if ( segme... | Null Coalescence and Lambdas |
C# | Is there C # feature to deconstruct tuple into subset fields of anoter tuple ? Thanks ! | public ( bool , int ) f1 ( ) = > ( true , 1 ) ; public ( double , bool , int ) f2 = > ( 1.0 , f1 ( ) /* ! ! here ! ! */ ) ; | C # tuple deconstructor inside another tuple constructor |
C# | I am writing a GetExpression ( ) which convert Model2 property to Model1 . When it comes to dynamic property , I try Convert.ToString ( f.Value ) or ( String ) f.Value but it said `` An expression tree may not contain a dynamic operation '' Anyone know what is the proper way to convert dynamic value to type value in ex... | public class Model1 { public String Value { get ; set ; } } public class Model2 { public dynamic Value { get ; set ; } } public static Expression < Func < Model2 , Model1 > > GetExpression ( ) { return f = > new Model1 { Value = f.Value } ; } | How to convert dynamic value to type value in expression |
C# | i need to resize 5000 images and save them in a separate folder . I have a code like this to create a resized copy of a picture ( found on the Internet ) : and I have this code , which first creates all the necessary directories to save pictures , and then starts changing all the images and saving them to new folders .... | Bitmap ResizeImage ( System.Drawing.Image image , int width , int height ) { var destRect = new System.Drawing.Rectangle ( 0 , 0 , width , height ) ; var destImage = new Bitmap ( width , height ) ; destImage.SetResolution ( image.HorizontalResolution , image.VerticalResolution ) ; using ( var graphics = Graphics.FromIm... | Out of memory exception when resizing many bitmaps |
C# | Can someone please help me with the following linq query ? I am gettting following error ; How to resolve ? | var userList = _context.Employee.AsQueryable ( ) ; var id = 1 ; userList = userList .Join ( _context.EmployeePermission , ul = > ul.EmployeeId , p = > p.EmployeeId , ( userlist , perm ) = > new { Employee = userList , Permisson = perm } ) .Where ( empAndPerm = > empAndPerm.Permisson.Trading > = 1 & & empAndPerm.Permiss... | Linq join ( ) - Join two entities and select one |
C# | If using .Net < 4.7 tuples are not supported . If I install the NuGet `` System.ValueTuple '' , I 'm able to write code likewith .Net 4.6.2 . How is that possible ? How can a NuGet ( DLL ) change my available language features ? Is there any documentation available about what is going on here ? I was n't able to find a... | public static ( string Name , int Age ) GetFoo ( ) { return ( `` Bar '' , 99 ) ; } | How does the System.ValueTuple NuGet expand my language features ? |
C# | I am dealing with an application that needs to randomly read an entire line of text from a series of potentially large text files ( ~3+ GB ) .The lines can be of a different length.In order to reduce GC and create unnecessary strings , I am using the solution provided at : Is there a better way to determine the number ... | // maps each line to it 's corresponding fileStream.position in the file List < int > _lineNumberToFileStreamPositionMapping = new List < int > ( ) ; public void ReadLine ( int lineNumber ) { var getStreamPosition = _lineNumberToFileStreamPositionMapping [ lineNumber ] ; // ... set the stream position , read the byte a... | How can I efficiently index a file ? |
C# | I was stepping through the debugger in some website database code , and ended execution before the database changes were applied . But they were still written to the database ! I tried to recreate the problem using a Windows Form application , and it did n't write to the database ( expected behaviour ) . I went back to... | < % @ Page Language= '' C # '' % > < % @ Import Namespace= '' System.Diagnostics '' % > < ! DOCTYPE html > < script runat= '' server '' > protected void Page_Load ( object sender , EventArgs e ) { using ( MsSqlDataContextDataContext db = new MsSqlDataContextDataContext ( ) ) { Product product = db.Products.First ( p = ... | USING block behaves differently in website vs windows form |
C# | I would like to fetch datas with checking id with some numbers.I use these codes but `` The LINQ expression node type 'ArrayIndex ' is not supported in LINQ to Entities . `` error appears . I guess questionID [ r ] is not supported in LINQ so what should I type instead of it . Thank you | int r = 0 ; var ask = from y in entity.sorulars where y.soru_id == questionID [ r ] select new { y.sorutipi_id } ; foreach ( var hold2 in ask ) { questionTypeID [ r ] = hold2.sorutipi_id ; r++ ; } | How to fix this ArrayIndex error ? |
C# | I 'm trying to add the Full Control permission ( for a NT service account ) to a folder through C # . However , the permission is not set , what I am missing here ? | var directoryInfo = new DirectoryInfo ( @ '' C : \Test '' ) ; var directorySecurity = directoryInfo.GetAccessControl ( ) ; directorySecurity.AddAccessRule ( new FileSystemAccessRule ( `` NT Service\\FileMoverService '' , FileSystemRights.FullControl , AccessControlType.Allow ) ) ; directoryInfo.SetAccessControl ( direc... | Can not set Full Control permission for folder |
C# | I am pretty new to C # dynamic keyword . In one of my projects I tried to play with it and encountered some unexpected behavior . I managed to reproduce the situation with the following code : I get a RuntimeBinderException saying 'System.DateTime ' does not contain a definition for 'Value'.So the variable date is trea... | class Program { static DateTime ? DateOnly ( DateTime ? time ) { return time.HasValue ? ( System.DateTime ? ) time.Value.Date : null ; } static void Main ( string [ ] args ) { dynamic now = System.DateTime.Now ; var date = DateOnly ( now ) ; Console.WriteLine ( date.Value ) ; // error thrown here Console.Read ( ) ; } } | Dynamic does not respect return type |
C# | I 've tested Class , Methods , Fields , Properties , and Enums to see if there are any cases when this is not true ? DotNetFiddle ExampleResults : Run-time exception ( line -1 ) : Are Not Equal : TestThisMethod ! = WorksAsExpected | using System ; public class Program { public static void Main ( ) { var fooType = typeof ( Foo ) ; ThrowIfNotEqual ( fooType.Name , nameof ( Foo ) ) ; var fi = fooType.GetField ( nameof ( Foo.field ) ) ; ThrowIfNotEqual ( fi.Name , nameof ( Foo.field ) ) ; var pi = fooType.GetProperty ( nameof ( Foo.property ) ) ; Thro... | Is it always the case that the nameof ( ) is equal to the typeof ( ) .Name ? |
C# | I have a list of objects of some class defined as and output that list as a table with property name as a column header ( full source code ) and get I want to have some custom titles , likeQuestion : How to define column titles for each property of the Person class ? Should I use custom attributes on properties or is t... | public class Person { public string FirstName { get ; set ; } public string LastName { get ; set ; } public int Age { get ; set ; } } var personList = new List < Person > ( ) ; personList.Add ( new Person { FirstName = `` Alex '' , LastName = `` Friedman '' , Age = 27 } ) ; var propertyArray = typeof ( T ) .GetProperti... | Define custom titles on properties of objects |
C# | example structure is : Is there a ( simple ) way to use GroupBy to get a group for every project with all the members as list ? When using foreach ( var group in members.GroupBy ( m = > m.Projects.First ( ) .Name ) ) it 's obviously only grouping by the first project for each member . But i want all possible projects w... | class Project { public string Name { get ; set ; } } class TeamMember { public string Email { get ; set ; } public List < Project > Projects { get ; set ; } } var projects = members.SelectMany ( m = > m.Projects ) .Select ( p = > p.Name ) .Distinct ( ) .ToList ( ) ; foreach ( var proj in projects ) { var relevantMember... | GroupBy on list property → object in each group |
C# | I am getting am error when I am trying to use platform invoke example where I am trying to change the Lower and Upper case of string.Here is what I got so far : I am not sure where I am going wrong with this but I think it is to do with the EntryPoint.I have to use Unicode and CharLowerBuffW did n't work either.How can... | class Program { [ DllImport ( `` User32.dll '' , EntryPoint = `` CharLowerBuffA '' , ExactSpelling = false , CharSet = CharSet.Unicode , SetLastError = true ) ] public static extern string CharLower ( string lpsz ) ; [ DllImport ( `` User32.dll '' , EntryPoint = `` CharUpperBuffA '' , ExactSpelling = false , CharSet = ... | Platform Invoke error attempted to read or write protected memory |
C# | I 've been looking at the source code of System.Reactive ( here ) , and it 's taken me down a rabbit hole to this place , where there is a Volatile.Read followed by Interlocked.CompareExchange , on the same variable : As I read it , the logic of this is `` if runDrainOnce is 0 and , if it was zero before I changed it t... | if ( Volatile.Read ( ref _runDrainOnce ) == 0 & & Interlocked.CompareExchange ( ref _runDrainOnce , 1 , 0 ) == 0 ) { //do something } private void Schedule ( ) { // Schedule the suspending drain once if ( Volatile.Read ( ref _runDrainOnce ) == 0 & & Interlocked.CompareExchange ( ref _runDrainOnce , 1 , 0 ) == 0 ) { _dr... | Combining Interlocked.Increment and Volatile.Write |
C# | I want to turn a full path into an environment variable path using c # Is this even possible ? i.e . | C : \Users\Username\Documents\Text.txt - > % USERPROFILE % \Documents\Text.txtC : \Windows\System32\cmd.exe - > % WINDIR % \System32\cmd.exeC : \Program Files\Program\Program.exe - > % PROGRAMFILES % \Program\Program.exe | Turn A Full Path Into A Path With Environment Variables |
C# | There was some code in my project that compared two double values to see if their difference exceeded 0 , such as : Resharper complained about this , suggesting I should use `` EPSILON '' and added just such a constant to the code ( when invited to do so ) . However , it does not create the constant itself or suggest w... | if ( totValue ! = 1.0 ) const double EPSILON = double.Epsilon ; // see http : //msdn.microsoft.com/en-us/library/system.double.epsilon.aspx . . .if ( Math.Abs ( totValue - 1.0 ) > EPSILON ) compValue = Convert.ToString ( totValue*Convert.ToDouble ( compValue ) ) ; const double EPSILON = 0.001 ; | Is this a good solution for R # 's complaint about loss of precision ? |
C# | I 'm using BrendanGrant.Helpers.FileAssociation ; ( a NuGet package ) to create file-associations for my application . It works fine so far . However , I have a problem with the ProgramVerbs : When I create a ProgramAssociation and add verbs to it like this : The Bearbeiten and Öffnen ( edit and open ) keywords are low... | var pai = new ProgramAssociationInfo ( fai.ProgID ) ; pai.Create ( `` App name '' , new [ ] { new ProgramVerb ( `` Öffnen '' , Assembly.GetEntryAssembly ( ) .Location + `` \ '' % 1\ '' '' ) , new ProgramVerb ( `` Bearbeiten '' , Assembly.GetEntryAssembly ( ) .Location + `` \ '' % 1\ '' '' ) } ) ; } | Why are my contextmenu entries lower case ? |
C# | I am a beginner with xaml ( for MVVM APPROACH ) using Silverlight . I read several documents and am a bit confused about it all . I would really appreciate if someone could explain the difference between the following.Suppose my XAML is : Now what is the difference between : I mean in MainPage.cs if I do `` this.DataCo... | xmlns : viewmodel= '' clr-namespace : smallMVVM '' ... ... ... ... < UserControl.Resources > < viewmodel : ViewModel x : Key= '' ViewModel '' / > < viewmodel : DatetimeToDateConverter x : Key= '' MyConverter '' / > < /UserControl.Resources > | Difference in xaml terms used for binding |
C# | I had thought that a Linq GroupBy would always produce unique keys , and yet when I project the results of a GroupBy into a Dictionary using .ToDictionary ( ) , I get an error saying `` an item with the same key has already been added '' : Here 's the code in question : [ Here Responsibilities is a DbSet of entities wh... | return DbContext.Responsibilities .GroupBy ( r = > r.RoleCode ) .ToDictionary ( g = > g.Key , g = > g.Count ( ) ) ; return DbContext.Responsibilities .GroupBy ( r = > r.RoleCode ) .Select ( g = > new { Code = g.Key , Count = g.Count ( ) } ) .ToDictionary ( i = > i.Code , i = > i.Count ) ; | Why do I get a `` key already added '' error when using the key from a GroupBy in ToDictionary ? |
C# | I have difficulty understanding why the multithreading fails to update values before the thread completes . Does the separate thread have its own copy of the references or values ? If not , to my understanding the code below should work properly when MyMethod is called , but often it does not create instances of some M... | class MyClass { static MyType [ ] obj = new MyType [ Environment.ProcessorCount - 1 ] ; void MyMethod ( ) { Thread [ ] threads = new Thread [ Environment.ProcessorCount - 1 ] ; for ( int i = 0 ; i < Environment.ProcessorCount - 1 ; i++ ) { threads [ i ] = new Thread ( ( ) = > FillObjects ( i ) ) ; threads [ i ] .Priori... | Multithreading issue updating the value |
C# | I have the following code , ( and I am completely aware about parameterized queries and SQL Injection ) : The problem is I have a lot of items and I have to execute the query for each of the items because the where clause will be complete in each step . I think if I will be able to make my query out side of my loop , m... | foreach ( var item in items ) { string query = `` select sum ( convert ( decimal ( 18,3 ) , tbl.Price ) ) p , sum ( convert ( decimal ( 18,2 ) , tbl.Sale ) ) s from table1 tbl `` + $ '' where tbl.ID = { item .ID } '' ; Execute ( query ) ; //Do stuff with query result } | Is there any way to make this query faster and build where clause outside of loop ? |
C# | When I look at the documentation for the .NET Char Struct ( here : https : //docs.microsoft.com/en-us/dotnet/api/system.char ) , I can see the usual properties , methods , etc. , as for any other Type defined in the .NET Framework.I know that the char struct has a -- operator defined for it as I can do the following : ... | char current = ' b ' ; current -- ; // current now holds the value a. public static Char operator -- ( char character ) { } | Where is the char struct -- operator defined in .NET ? |
C# | Is it possible to perform an explicit Where query on the Entity Framework cache ? I know that I can use Find to look for an entity in the cache ( based on the entities primary key ) . Code sample : | var person = new PersonToStoreInDb ( ) { Id = 1 , Name = `` John '' } ; dbSet.Add ( person ) ; // Perform some other code ... // DbContext.SaveChanges was NOT called ! var personFromDbSet = bSet.Where ( p = > p.Name == `` John '' ) .First ( ) ; // personFromDbSet is null because it was not sent towards DB via SaveChang... | Query Entitiy Framework cache |
C# | I am using .NET 's Regex to capture information from a string . I have a pattern of numbers enclosed in bar characters , and I want to pick out the numbers . Here 's my code : However , testMatch.Captures only has 1 entry , which is equal to the whole string . Why does n't it have 3 entries , 12 , 13 , and 14 ? What am... | string testStr = `` |12||13||14| '' ; var testMatch = Regex.Match ( testStr , @ '' ^ ( ? : \| ( [ 0-9 ] + ) \| ) + $ '' ) ; | Why am I not getting all my regex captures ? |
C# | I 'm working on ASP.NET Core 3.1 application . I want to perform some final actions related to database while my application is about to stop . To do that I 'm trying to call a function in my scoped service which is a additional layer between database and ASP.NET Core.Startup.csBut unfortunately i get Can not resolve s... | public void Configure ( IApplicationBuilder app , IHostApplicationLifetime lifetime ) { lifetime.ApplicationStopping.Register ( ( ) = > { app.ApplicationServices.GetService < MyService > ( ) .SynchronizeChanges ( ) ; } ) ; } | ASP.Net Core How to perform final actions on database when application is about to stop |
C# | If I have an interface with a method that returns a collection of something , is it possible to return an implementation of the collection type instead ? For example : If not , why not ? At least to me , this makes sense . | public interface IVehicle { IEnumerable < Part > GetParts ( int id ) ; } public class Car : IVehicle { List < Part > GetParts ( int id ) { //return list of car parts } } public class Train : IVehicle { IEnumerable < Part > GetParts ( int id ) { //return IEnumerable of train parts } } | Changing Collection type from Interface to Implementing class |
C# | How can I set TotalHours to be in double format , or what I need to do to get the result in txtBoxMonatstotal as a result of 93.3.This is my code : The current result looks like this : Thank you for your help | private void calendar1_MonthChanged ( object sender , EventArgs e ) { DateTime start = new DateTime ( calendar1.CurrentDate.Year , calendar1.CurrentDate.Month , 1 ) ; DateTime stop = new DateTime ( calendar1.CurrentDate.Year , calendar1.CurrentDate.Month , 1 ) .AddMonths ( 1 ) .AddDays ( -1 ) ; int numberOfWorkDays = G... | Double-formatting on time |
C# | I am testing object like this : But that does n't match all of the other combination of types < sting , object > , < int , string > etc ... I just want to know if it has implemented the interface regardless of what generic types it is using.I found an example that said it was possible doing something like : But I still... | if ( item is IDictionary < object , object > ) dictionary.GetType ( ) .GetInterfaces ( ) .Any ( x = > x.GetGenericTypeDefinition == typeof ( IDictionary < > ) ) ; | Is it possible to see if an object inherits IDictionary without generic type parameters ? |
C# | I am creating a substring from a string with non-combining diacritics that follow a space . When doing so , I check the string with .Contains ( ) and then perform the substring . When I use a space char inside of an .IndexOf ( ) , the program performs as expected , yet when using the string `` `` , within .IndexOf ( ) ... | string a = `` aɪ prɪˈzɛnt '' ; string b = `` maɪ ˈprɛznt '' ; // A Console.WriteLine ( a.IndexOf ( `` `` ) ) ; // string index : 2Console.WriteLine ( a.IndexOf ( ' ' ) ) ; // char index : 2// B Console.WriteLine ( b.IndexOf ( `` `` ) ) ; // string index : -1Console.WriteLine ( b.IndexOf ( ' ' ) ) ; // char index : 3 co... | Why does a space preceding a non-combining diacritic function differently when using IndexOf ( string ) and IndexOf ( char ) ? |
C# | BackgourndI am currently trying to add a value to a list of a model however it seems to be different than how I would do it in JavaScript.ModelFunction To Add ValueQuestionI am trying to add the result from HtmlAttribute att = img.Attributes [ `` src '' ] ; into string [ ] images of my list . That way once I complete t... | public class ContentBase { public string Name { get ; set ; } public string Description { get ; set ; } public string LastModifiedTime { get ; set ; } public string KeyWords { get ; set ; } public string Content { get ; set ; } public string UniqueId { get ; set ; } public string library { get ; set ; } public string C... | Adding a value to a List which is based on a Model |
C# | I am currently working on an implementation of lazy locating self hosted WCF services . These services define their contracts in a common interface to client and host which has to be inherited from IWCFServiceBase.After the WCFHost hosts an interface specified by a type parameter constrained by IWCFServiceBase : public... | public WCFClient < T > GetMicroService < T > ( string servicename , T contract ) where T : IWCFServiceBase { if ( this.Services.ContainsKey ( servicename ) & & this.Services [ servicename ] .ContainsKey ( contract ) ) { return this.Services [ servicename ] [ contract ] ; } } | Type parameter constraint does n't seem to apply to the returned type |
C# | This is similar to my previous question : Downloading images from publicly shared folder on DropboxI have this piece of code ( simplified version ) that needs to download all images from publicly shared folder and all sub-folders . How do I list entries of all sub-folders ? | using Dropbox.Api ; using Dropbox.Api.Files ; ... // AccessToken - get it from app console // FolderToDownload - https : //www.dropbox.com/sh/ { unicorn_string } ? dl=0using ( var dbx = new DropboxClient ( _dropboxSettings.AccessToken ) ) { var sharedLink = new SharedLink ( _dropboxSettings.FolderToDownload ) ; var sha... | Downloading images from publicly shared folders and sub-folders on Dropbox |
C# | I have 2 strings of the same length.I was assuming ( probably wrongly ) that inserting a space between each character of each string will not change their order.If I insert other characters ( _ x for instance ) , the order is preserved . What 's going on ? Thanks in advance . | var e1 = `` 12*4 '' ; var e2 = `` 12-4 '' ; Console.WriteLine ( String.Compare ( e1 , e2 ) ) ; // -1 ( e1 < e2 ) var f1 = `` 1 2 * 4 '' ; var f2 = `` 1 2 - 4 '' ; Console.WriteLine ( String.Compare ( f1 , f2 ) ) ; // +1 ( f1 > f2 ) | Inserting spaces between chars of two strings modify their order |
C# | So , I 've been working on an app that consumes REST API requests , however , for some reason , the API gets unresponsive randomly ( sometimes it gives a response within 3 seconds and sometimes the request will take so long that it throws a timeOutexception ) so Whenever I consume a call I use this code to restart the ... | bool taskCompletion = false ; while ( taskCompletion == false ) { try { using ( CancellationTokenSource cts = new CancellationTokenSource ( ) ) { cts.CancelAfter ( timeSpan ) ; await task ( cts.Token ) ; taskCompletion = true ; } } catch ( OperationCanceledException ) { taskCompletion = false ; } } public static async ... | c # : Restart an Async task after certain time passes before completion |
C# | I have an updater , which is called via the main program once an update is detected ( from a remote XML file ) , first it checks whether the process is open ( this gets run for every process until it finds it ( foreach loop ) ) the updater then downloads the file : and then it attempts to delete the current one and ren... | if ( clsProcess.ProcessName.ToLower ( ) .Contains ( `` conkinator-bot.exe '' ) ) { clsProcess.CloseMainWindow ( ) ; return true ; } client.DownloadFile ( url , `` Conkinator-Bot-new.exe '' ) ; File.Delete ( `` Conkinator-Bot.exe '' ) ; File.Move ( `` Conkinator-Bot-new.exe '' , `` Conkinator-Bot.exe '' ) ; | My updater is failing to close my main program ( C # ) |
C# | My understanding of Actions in C # is that they are just a specific version of a delegate , namely one with no parameters and no return type.If I create a class like this ... ... it wo n't compile since I have n't created an instance of the delegate . However if I replace the delegate definition with that of an Action ... | class TrainSignal { public delegate void TrainsAComing ( ) ; public void HerComesATrain ( ) { TrainsAComing ( ) ; } } class TrainSignal { public Action TrainsAComing ; public void HerComesATrain ( ) { TrainsAComing ( ) ; } } | Why is it legal to invoke an Action without have first assigned it to anything ? |
C# | This function is used to return a contact list for a users search input . The number of search terms is always at least one , but could be many.The problem is in the loop . Only the last search term is ever used , even though the generated sql looks correct ( as in the correct amount of clauses are generated for the nu... | public IList < Contact > GetContacts ( string [ ] searchTerms ) { using ( dbDataContext db = new dbDataContext ( ) ) { var contacts = from _contacts in db.Contacts orderby _contacts.LastName ascending , _contacts.FirstName ascending select _contacts ; foreach ( string term in searchTerms ) { contacts = ( IOrderedQuerya... | What is the correct way to dynamically add an undetermined number of clauses to a Linq 2 Sql query ? |
C# | There is a methods which is accepting a parameter of type List < long ? > , I need to assign it to someTestModel ids , which are of type ISet < long > . | public void testM1 ( List < long ? > testIds ) { var request = new someTestModel { ids= testIds } ; } | How to convert List < long ? > to ISet < long > |
C# | I use EF Core with code-first and I have model Company and model Contact.And I try to set relationships between them via FluentAPI in OnModelCreating method through modelBuilder . Which one of them is correct and is there any difference ? | public class Company { public Guid Id { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } public DateTime FoundationDate { get ; set ; } public string Address { get ; set ; } public string Email { get ; set ; } public string Phone { get ; set ; } public string Logo { get ; set ;... | What 's the difference between two opposite modelBuilder relationship settings ? |
C# | I 'm wanting to consolidate all my error logging down to a single method that can call from all over my application when we handle exceptions . I have a few awkward constraints I will describe below.I have parsed the stack before but the code ends up ugly and depending on the stack it can mess up.All I really want is w... | public void Log ( Exception ex ) { string innerMessage = `` '' ; if ( ex.InnerException ! = null ) { innerMessage = ex.InnerException.Message ; } Console.WriteLine ( $ '' Message : { ex.Message } # Location : { ex.StackTrace } # InnerMessasge : { innerMessage } '' ) ; } | Get exception location into Logger method without parsing stack ? |
C# | I 'm currently having some issues with getting my SelectList to default to a defined initial value . I created a snippet to demonstrate the issue : https : //dotnetfiddle.net/ozroT1Essentially I want my DropDownList to display [ null,1,2,3,4,5 ] which will map to Model.ChosenNumber.The model I have for this looks is re... | public class SampleViewModel { public int ? ChosenNumber ; public IEnumerable < SelectListItem > PickList ; } List < SelectListItem > pickNumberList = new List < SelectListItem > ( ) ; pickNumberList.AddRange ( Enumerable.Range ( 1 , 5 ) .Select ( l = > new SelectListItem { Text = l.ToString ( ) , Value = l.ToString ( ... | SelectList does not select correct value |
C# | I made a WPF program that works in the VIsual studio when run . I made an installer for my program with Visual Installer Projects 2017 . At one part the program crashes and I get the following dialog : An unhandled Microsoft.NET Framework exception occured in Program1.exe [ 10204 ] .My catch block looks like thisMessag... | Dispatcher.Invoke ( new Action ( ( ) = > { EnableContent ( ) ; } ) ) ; } catch ( AggregateException e ) { MessageBox.Show ( e.ToString ( ) ) ; Dispatcher.Invoke ( new Action ( ( ) = > { UpdateLoadMsg ( `` No internet connection . `` , MsgType.FAIL ) ; } ) ) ; } catch ( Exception e ) { MessageBox.Show ( e.ToString ( ) )... | Exception is not being caught when program installed with a msi file |
C# | Give the example code below , can anyone explain why the first typeof ( ) call works successfully but the second fails ? ? It does n't matter if they are classes or interfaces it fails either way . | interface ITestOne < T1 > { T1 MyMethod ( ) ; } interface ITestMany < T1 , T2 > { T1 MyMethod ( T2 myParameter ) ; } void Main ( ) { var typeOne = typeof ( ITestOne < > ) ; //This line works var typeTwo = typeof ( ITestMany < > ) ; //Compile error } | Unable to get the type of an interface/class using more than one generic type ? |
C# | I have below c # method to compare two data tables and return the mismatch records.This code works , but it takes 1.24 minutes to compare 10,000 records in the datatable . Any way to make this faster ? N is the primary key and columnName is the column to compare.Thanks . | public DataTable GetTableDiff ( DataTable dt1 , DataTable dt2 , string columnName ) { var StartTime = DateTime.Now ; dt1.PrimaryKey = new DataColumn [ ] { dt1.Columns [ `` N '' ] } ; dt2.PrimaryKey = new DataColumn [ ] { dt2.Columns [ `` N '' ] } ; DataTable dtDifference = null ; //Get the difference of two datatables ... | Effecient way to compare data tables |
C# | Why does the following code give a compile error for the generic case ? Am I missing something or is n't it given that every TItem must be an IFoo and therefore it 's impossible for this construct to violate type safety ? | abstract class Test < TItem > where TItem : IFoo { public IEnumerable < IFoo > Foos { get ; set ; } public void Assign ( ) { Foos = GetSomeSpecificList ( ) ; // works as expected Foos = GetSomeGenericList ( ) ; // compile error ? } protected abstract ICollection < TItem > GetSomeGenericList ( ) ; protected abstract ICo... | Covariance and generic types |
C# | Both of the following variations compile and on the surface seem to behave in the same way . Aside from syntax sugar are there any other differences ? | someObject.SomeEvent += new SomeEventHandler ( someObject_SomeEvent ) ; someObject.SomeEvent += someObject_SomeEvent ; | Should event handlers be decorated with their delegate ? |
C# | I 'm trying to run some slightly-modified code from an MSDN article as part of a school project . The goal is to use a colormatrix to recolor a bitmap in a picture box . Here 's my code : where rScale , gScale , and bScale are floats with values from 0.0f to 1 . The original MSDN article is here : https : //msdn.micros... | float [ ] [ ] colorMatrixElements = { new float [ ] { rScale , 0 , 0 , 0 } , new float [ ] { 0 , gScale , 0 , 0 } , new float [ ] { 0 , 0 , bScale , 0 } , new float [ ] { 0 , 0 , 0 , 1 } } ; ColorMatrix colorMatrix = new ColorMatrix ( colorMatrixElements ) ; | C # ColorMatrix Index out of Bounds |
C# | Let 's say I have the following data in a database.How can I write a LINQ query to get the sum of ValueA and also the sum of ValueB for all rows with Category == 1 ? I know I could load all the data and then use Sum on the loaded data but would prefer to total them in the database.I know I can use group by but I 'm not... | class Data { public int Category { get ; set ; } public int ValueA { get ; set ; } public int ValueB { get ; set ; } } | How to use LINQ to get multiple totals |
C# | I 'm writing code in a C # library to do clustering on a ( two-dimensional ) dataset - essentially breaking the data up into groups or clusters . To be useful , the library needs to take in `` generic '' or `` custom '' data , cluster it , and return the clustered data . To do this , I need to assume that each datum in... | public interface IPoint { double Lat { get ; set ; } double Lng { get ; set ; } } public class ClusterableStop : GTFS.Entities.Stop , IPoint { public ClusterableStop ( Stop stop ) { Id = stop.Id ; Code = stop.Code ; Name = stop.Name ; Description = stop.Description ; Latitude = stop.Latitude ; Longitude = stop.Longitud... | Passing in and returning custom data - are interfaces the right approach ? |
C# | I 'd like to have a After which I should be able to search an integer optimally in the data structure and get corresponding value.Example : Could anyone suggest ? | data structure with < Key , Value > where Key = ( start , end ) , Value = string var lookup = new Something < ( int , int ) , string > ( ) { { ( 1,100 ) , '' In 100s '' } , { ( 101,200 ) , '' In 100-200 '' } , } var value1 = lookup [ 10 ] ; //value1 = `` In 100s '' var value2 = lookup [ 110 ] ; //value2 = `` In 100-200... | I want to have data structure with ( start , end ) as key and then be able to search integer in whole data structure and get corresponding value |
C# | I 've got a StoreOwner entity . StoreOwner has a Store property . I 've got the following user story : As a store owner , I can add a product to my store.Where should the behavior of `` adding the product to the store '' live ? On the StoreOwner or the Store ? If it 's the store , what would the method name be ? | public class Product { } public class Store { public IEnumerable < Product > Products { get ; private set ; } } public class StoreOwner { public Store Store { get ; private set } } | Where should behavior live when the user story mentions the parent , but the action is upon a child ? |
C# | Using the full version of Visual C # 2008 Express , it looks like you could useBut is there a similar way using Express ? | devenv SolutionFile | ProjectFile /upgrade | Is it possible to do a command line project upgrade and compile from Visual C # 2005 to Visual C # 2008 Express ? |
C# | I have a combo box called comboFileTypes . Inside that is a drop down list containing : And after a button press I have the following code to scan a directory for files : Which is hardcoded . I want the WHERE option to be dynamically generated from the combobox instead , so that the user can add another type of file if... | MP4MOVMKVVOB var files = Directory .EnumerateFiles ( sourceDIR.Text , `` * . * '' , SearchOption.AllDirectories ) .Where ( s = > s.EndsWith ( `` .mp4 '' ) || s.EndsWith ( `` .mov '' ) || s.EndsWith ( `` .vob '' ) || s.EndsWith ( `` .MP4 '' ) || s.EndsWith ( `` .MOV '' ) || s.EndsWith ( `` .VOB '' ) ) ; | Dynamically adding .EndsWith ( ) from combobox |
C# | In this example there are two functions , TaskFunc and ThreadFunc , which are called from MainFunc seperately . I am curious as to why the second method does n't seem to have any effect , and seems to be skipped . Not even the Thread.Sleep ( ... ) seems to get executed.As you can see , the total execution time for Thre... | private static async Task MainFunc ( ) { var watch = System.Diagnostics.Stopwatch.StartNew ( ) ; List < Task < int > > list = new List < Task < int > > ( ) ; for ( int i = 1 ; i < = 3 ; i++ ) { list.Add ( TaskFunc ( i ) ) ; } var taskResult = await Task.WhenAll ( list ) ; foreach ( var item in taskResult ) { Console.Wr... | Task.Delay vs Thread.Sleep difference |
C# | I witnessed something strange when initializing a class with a List as a property . When doing thisIt compiles , and crashes saying that list is null . So , adding this to Stuff 's constructor : List is now initialized to contain { 1 , 2 , 3 } which seems to make some sense . But then , changing the constructor toAnd i... | var stuff = new Stuff ( ) { list = { 1 , 2 , 3 } } ; public Stuff ( ) { list = new List < int > ( ) ; } public Stuff ( ) { list = new List < int > ( ) { 1 , 2 , 3 } ; } var stuff = new Stuff ( ) { list = { 4 , 5 , 6 } } ; | Initializer syntax for list properties |
C# | I find it easier to ask this question through a code example.If I was n't privy to the above assignments , how would I determine if firstParent was created from the instance firstChild without accessing/comparing their fields or properties ? | class Parent { } class Child : Parent { } ... ... Child firstChild = new Child ( ) ; Child secondChild = new Child ( ) ; Parent firstParent = ( Parent ) firstChild ; Parent secondParent = ( Parent ) secondChild ; | How to tell if an instance of a parent class was created from an instance of a particular child |
C# | I have a simple task to transponse a square 2D array : ( I need to do it in a very plain manner , no containers etc ) I was expecting a reversed array as the output . However , I got the same array here . Please , help me find out what did I do wrong ? | static void Main ( string [ ] args ) { double [ , ] a = new double [ 5 , 5 ] ; Random random = new Random ( ) ; for ( int i = 0 ; i < 5 ; i++ ) { for ( int j = 0 ; j < 5 ; j++ ) { a [ i , j ] = random.NextDouble ( ) ; } } for ( int i = 0 ; i < 5 ; i++ ) { for ( int j = 0 ; j < 5 ; j++ ) { Console.Write ( a [ i , j ] + ... | The 2D array wo n't transponse c # |
C# | In an example , I find this code : I would like to understand the reason for the line : Can we not just do it this way : Are there some advantages/disadvantages to either way of doing it ? | public event EventHandler ThresholdReached ; protected virtual void OnThresholdReached ( EventArgs e ) { EventHandler handler = ThresholdReached ; if ( handler ! = null ) handler ( this , e ) ; } EventHandler handler = ThresholdReached ; public event EventHandler ThresholdReached ; protected virtual void OnThresholdRea... | Why copy an event handler into another variable |
C# | When looking at Microsoft 's implementation of various C # LINQ methods , I noticed that the public extension methods are mere wrappers that return the actual implementation in the form of a separate iterator function.For example ( from System.Linq.Enumerable.cs ) : What is the reason for wrapping the iterator like tha... | public static IEnumerable < TSource > Concat < TSource > ( this IEnumerable < TSource > first , IEnumerable < TSource > second ) { if ( first == null ) throw Error.ArgumentNull ( `` first '' ) ; if ( second == null ) throw Error.ArgumentNull ( `` second '' ) ; return ConcatIterator < TSource > ( first , second ) ; } st... | Why use wrappers around the actual iterator functions in LINQ extension methods ? |
C# | I have a simple method containing a query to calculate some values.My aim is to modify the method to allow me to specify the x.ThisValue field being queried in the object.If I were to specify the Where clause of my query , I might pass a predicate but in this case , I only want to alter the value of x.ThisValue.Ideally... | private decimal MyQueryBuilderMethod ( List < ThingsViewModel > myThings ) { return myThings.Where ( x = > x.Id == 1 ) .Select ( x = > ( x.ThisValue * x.That ) ) .Sum ( ) ; } private decimal MyQueryBuilderMethod ( List < ThingsViewModel > myThings , Func < ThingsViewModel , bool > predicates ) { return myThings.Where (... | How could I use Func < > to modify a single condition of a lambda |
C# | I am looking at the article from MSDN Guidelines for Overloading Equals ( ) and Operator ==and I saw the following codethe strange thing is the cast to object in the second ifWhy p is casted again to object ? Is n't it enough to write thisIf p can not be casted to TwoDPoint , then it 's value will be null . I am puzzle... | public override bool Equals ( object obj ) { // If parameter is null return false . if ( obj == null ) { return false ; } // If parameter can not be cast to Point return false . TwoDPoint p = obj as TwoDPoint ; if ( ( System.Object ) p == null ) { return false ; } // Return true if the fields match : return ( x == p.x ... | Strange cast in Equals override provided by MSDN |
C# | My code currently looks like this : Is there now another cleaner way that I could do this null check using the `` ? '' that was added to the latest version of C # ? | if ( control ! = null & & control.Meta ! = null & & control.State ! = null ) { ConfigureMeta ( control , control.Meta ) ; ConfigureColors ( control , control.State ) ; } | Is there a cleaner way to handle null checking now that the ? test exists for a variable ? |
C# | It seems that StateHasChanged ( ) only triggers the re-render of the component after an await operation on a Task ( found here ) .So I want to use only StateHasChanged for re-rendering rather than using Task.delay or Task.Run.Here is my code : Here I use loader which is activate using IsBusy . But It is not working the... | protected async Task ClearSearch ( ) { SearchTestCoupon = new Mechanic.Shared.TestCouponSearch ( ) ; IsBusy = true ; TestCouponGroups = new List < Mechanic.Shared.TestCouponGroup > ( ) ; StateHasChanged ( ) ; // < < -- -- -- -- **FIRST TIME** //await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; await GetTestCouponGroups... | StateHasChanged not detecting changes first time |
C# | Given the following simple code : and running it in the Release mode with MSVS2015 ( .NET 4.6 ) we will get a never ending application . That happens because the JIT-compiler generates code which reads finish only once , hence ignoring any future updates . The question is : why is the JIT-compiler allowed to do such an... | class Program { static bool finish = false ; static void Main ( string [ ] args ) { new Thread ( ThreadProc ) .Start ( ) ; int x = 0 ; while ( ! finish ) { x++ ; } } static void ThreadProc ( ) { Thread.Sleep ( 1000 ) ; finish = true ; } } | Read elimination and concurrency |
C# | Let 's say I have the following method defined : Now , let 's say that I also have the following two methods defined ; a regular method : void Print ( Func < int , int > function ) and an extension method : static void Print ( this Func < int , int > function ) I can call the former like this : Print ( ReturnNumber ) ;... | int ReturnNumber ( int number ) { return number ; } | Type inference discrepancy between method and extension method arguments |
C# | I have an table with Guid as primary key . The table has contained a lot of rows already . Also , I have an win service , that do some set of actions with each row ( possible needs read and write data from another databases ) . So processing of one row takes a quite lot of time . ( in average about 100 seconds ) My win... | public class MyDto { public Guid Id { get ; set ; } } while ( true ) { if ( time to start ) { List < MyDto > rows = LoadData ( ) ; foreach ( MyDto obj in rows ) { Process ( obj ) ; //it takes in average about 100 sec } } } public List < MyDto > LoadData ( int winServInstanceNumber ) { } //on .net sideobj.Id.GetHashCode... | I need an contributon function for my win service instances |
C# | I was trying to add some non-production test code by creating a 3rd partial file in addition to MyPage.aspx and MyPage.aspx.cs and MyPage.aspx.designer.cs . I called my third file MyPage.aspx.TEST.csIn the partial file MyPage.aspx.TEST.cs , I wrote the following : The code compiles and I then decompile the code and the... | protected override void OnInit ( EventArgs e ) { Page.LoadComplete += RunTest ; base.OnInit ( e ) ; } //Assert.public void RunTest ( object sender , EventArgs e ) { //Clever assertions } | Why might an event not register when it is a part of a 3rd partial file in ASP.NET ? |
C# | How to select many split string and group by with another members in linq ? I have a list of Log Data Which have a many log datum.The index pattern is the set of log index which use the delimiter `` , '' .And i want split index patterns and group by all member like this.And i write linq like this to group by first..But... | class LogData { public string IndexPattern { get ; set ; } public string Version { get ; set ; } public string Type1 { get ; set ; } public string Type2 { get ; set ; } //here has a constructor of this class } List < LogData > logList = new List < LogData > ( ) ; logList.add ( new LogData ( `` 1,2,4 '' , `` Ver1 '' , `... | How to select each splited string and group by with another members in linq ? |
C# | I have a problem , after adding this code so I can access my MainWindow controls in Downloader class : andit now gives me `` An unhandled exception of type 'System.StackOverflowException ' occurred in System.Windows.Forms.dll '' on linein MainWindow.Designer.cs . If i comment out the code above , it works fine . Any id... | public partial class MainWindow : Form { private Downloader fileDownloader ; public MainWindow ( ) { InitializeComponent ( ) ; fileDownloader = new Downloader ( this ) ; } //smth } class Downloader : MainWindow { private MainWindow _controlsRef ; public Downloader ( MainWindow _controlsRef ) { this._controlsRef = _cont... | Stack Overflow when trying to access form controls from class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.