text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have the following problem : After I add a string to my number the second digit after the point disappears like thisThe output is 37,4 when it should be 37,40 with one more digit after the comma . How do I fix this problem ? When I print it without adding the last piece of string the output of the integer is correct . <code> var needed_product = sets * ( 2 * price_bananas ) + sets * ( 4 * price_eggs ) + sets * ( 0.2 * price_berries ) ; var difference = Math.Abs ( needed_product - amount_cash ) ; if ( amount_cash > =needed_product ) { Console.Write ( `` Ivancho has enough money - it would cost `` + `` { 0 : F2 } '' , needed_product + `` lv . `` ) ; }
C # Numbers after decimal disappear after I join them with a string
C_sharp : What 's a good collection in C # to store the data below : I have check boxes that bring in a subjectId , varnumber , varname , and title associated with each checkbox.I need a collection that can be any size , something like ArrayList maybe with maybe : Any good ideas ? <code> list [ i ] [ subjectid ] = x ; list [ i ] [ varnumber ] = x ; list [ i ] [ varname ] = x ; list [ i ] [ title ] = x ;
A Good C # Collection
C_sharp : Let 's say we have a project that will handle lots of data ( employees , schedules , calendars ... .and lots more ) . Client is Windows App , Server side is WCF . Database is MS SQL Server . I am confused regarding which approach to use . I read few articles and blogs they all seem nice but I am confused . I do n't want to start with one approach and then regret not choosing the other . The project will have around 30-35 different object types . A lot of Data retrieving to populate different reports ... etcApproach 1 : Then Helper classes to deal with data saving and retrieving : FYI , The object classes like Employees and Assignment will be in a separate Assembly to be shared between Sever and Client.Anyway , with this approach I will have a cleaner objects . The Helper classes will do most of the job . Approach 2 : With this approach , Each object will do its own job.. Data still can be transferred from WCF to client easily since WCF will only share properties . Approach 3 : Using Entity Framework.. beside the fact that I never worked with it ( which is nice since I have to learn something new ) I will need to create POCOs to transfer data between client and WCF.. Now , Which is better ? more options ? <code> // classes that hold datapublic class Employee { public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } ... .. } public class Assignment { public int Id { get ; set ; } public int UserId { get ; set ; } public DateTime Date { get ; set ; } ... .. } ... .. public static class Employees { public static int Save ( Employee emp ) { // save the employee } public static Employee Get ( int empId ) { // return the ugly employee } ... .. } public static class Assignments { public static int Save ( Assignment ass ) { // save the Assignment } ... .. } // classes that hold data and methods for saving and retrievingpublic class Employee { // constructors public Employee ( ) { // Construct a new Employee } public Employee ( int Id ) { // Construct a new Employee and fills the data from db } public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } ... .. public int Save ( ) { // save the Employee } ... .. } public class Assignment { // constructors public Assignment ( ) { // Construct a new assignment } public Assignment ( int Id ) { // Construct a new assignment and fills the data from db } public int Id { get ; set ; } public int UserId { get ; set ; } public DateTime Date { get ; set ; } ... .. public int Save ( ) { // save the Assignment } ... .. } ... ..
which design is better for a client/server project with lots of data sharing
C_sharp : Have Have How can I search lbyte for not just a single byte but for the index of the searchBytes ? E.G.Here is the brute force I came up with.Not the performance I am looking for . <code> List < byte > lbyte byte [ ] searchBytes Int32 index = lbyte.FirstIndexOf ( searchBytes ) ; public static Int32 ListIndexOfArray ( List < byte > lb , byte [ ] sbs ) { if ( sbs == null ) return -1 ; if ( sbs.Length == 0 ) return -1 ; if ( sbs.Length > 8 ) return -1 ; if ( sbs.Length == 1 ) return lb.FirstOrDefault ( x = > x == sbs [ 0 ] ) ; Int32 sbsLen = sbs.Length ; Int32 sbsCurMatch = 0 ; for ( int i = 0 ; i < lb.Count ; i++ ) { if ( lb [ i ] == sbs [ sbsCurMatch ] ) { sbsCurMatch++ ; if ( sbsCurMatch == sbsLen ) { //int index = lb.FindIndex ( e = > sbs.All ( f = > f.Equals ( e ) ) ) ; // fails to find a match IndexOfArray = i - sbsLen + 1 ; return ; } } else { sbsCurMatch = 0 ; } } return -1 ; }
Search for an Array or List in a List
C_sharp : Consider the following code : As expected , the non-generic DoSomething method will be invoked . Now consider the following modification : The only thing I 've changed is adding the T type parameter to the second overload , thus making it generic . Note that the type parameter is not used.That modification causes the first DoSomething method to be called . Why ? The compiler has all the information it needs in order to choose the second method.Can you please explain why , or even better , point me to the section of the C # specification that explains this behavior ? <code> public class Tests { public void Test ( ) { Assert.AreEqual ( `` Int '' , DoSomething ( 1 ) ) ; } public static string DoSomething < T > ( T value ) { return `` Generic '' ; } public static string DoSomething ( int value ) { return `` Int '' ; } } public class Tests { public void Test ( ) { Assert.AreEqual ( `` Int '' , DoSomething ( 1 ) ) ; } public static string DoSomething < T > ( T value ) { return `` Generic '' ; } public static string DoSomething < T > ( int value ) { return `` Int '' ; } }
Generic Method Resolution
C_sharp : How can I generate types like these using the System.Reflection.Emit libraries : When I call ModuleBuilder.DefineType ( string ) with the second type declaration , I get an exception because there is already another type in the module with the same name ( I 've already defined the type parameter on the first type ) . Any ideas ? <code> public class Test < T > { } public class Test < T1 , T2 > { }
How can I define multiple types with the same name and different type parameters using Reflection Emit ?
C_sharp : I have a collection of first names which I need to combine into a comma separated string.The generated string needs to adhere to proper grammar.If the collection contains one name , then the output should be just that name : If the collection contains two names , then the output should be separated by the word `` and '' : If the collection contains three or more names , then the output should be comma delimited , and the last name should have the word `` and '' before it : Here is the code I came up with . Its not very elegant and I 'd like to know if there is a better way to accomplish this in C # ( 4.0 is OK ) . <code> John John and Mary John , Mary , and Jane List < string > firstNames = new List < string > ( ) ; firstNames.Add ( `` John '' ) ; firstNames.Add ( `` Mary '' ) ; firstNames.Add ( `` Jane '' ) ; string names = string.Empty ; for ( int i = 0 ; i < firstNames.Count ; i++ ) { if ( i == 1 & & firstNames.Count == 2 ) { names += `` and `` ; } else if ( firstNames.Count > 2 & & i > 0 & & i ! = firstNames.Count - 1 ) { names += `` , `` ; } else if ( i ! = 0 & & i == firstNames.Count - 1 ) { names += `` , and `` ; } names += firstNames [ i ] ; }
How to Build String from a Collection of Names
C_sharp : As you all know , in C # we could not do something like this : ororBut this code compiles successfully and in debug mode I can see that type of the voidObject is System.Void : What is this ? Is this real instance of void ? <code> var voidObject = new void ( ) ; var voidObject = new System.Void ( ) ; var voidObject = Activator.CreateInstance ( typeof ( void ) ) ; var voidObject = FormatterServices.GetUninitializedObject ( typeof ( void ) ) ;
Did I instantiate an object of void ?
C_sharp : Does someone have a script or snippet for Visual Studio that automatically removes comment headers for functions or classes ? I want to remove comments like.Actually anything that removes comments starting with /// would really help . We have projects with massive amount of GhostDoc comment that really just hides the code and we are not using the document output . It is a tedious work for us to remove theese comments . <code> /// < summary > /// /// < /summary >
How can I automate the removal of XML Documentation Comments ?
C_sharp : I 'm having this really weird problem with a conditional statement when setting an Action < T > value . It 's not that I do n't know how to work around this as it 's pretty easy to solve by using a normal if.Here 's my problem : This gives me a compiler error with the message There 's no implicit conversion between 'method group ' and 'method group'.Which is strange as I ca n't figure out why this would be illegal.By the way , the below syntax will make this valid ( from the compilers point of view ) : So maybe you can read the question as , why is the cast necessary ? <code> public class Test { public bool Foo { get ; set ; } public Action < bool > Action { get ; set ; } public void A ( ) { Action = Foo ? B : C ; //Gives compiler error } public void B ( bool value ) { } public void C ( bool value ) { } } public void A ( ) { Action = Foo ? ( Action < bool > ) B : C ; }
Conditional statement , generic delegate unnecessary cast
C_sharp : I am confusing about using == in ( c # ) when I use literal string like here : the comparison a==b will be true.but when I use object like here : the comparison a==b will be false.even though a , b , c , d all of type System.Object in compile time and == operator compare values depends on their values in compile time.I use extension method to get type of varabiles during compile time : <code> object a= '' hello '' ; object b= '' hello '' ; object c=new StringBuilder ( `` hello '' ) .ToString ( ) ; object d=new StringBuilder ( `` hello '' ) .ToString ( ) ; public static class MiscExtensions { public static Type GetCompileTimeType < T > ( this T dummy ) { return typeof ( T ) ; } }
confusing of using == operator in c #
C_sharp : Regex is on string 's only , but what if that functionality can be extended to not only character but objects or even further to functions ? Suppose our object 's will be integers , they can be in any order : And the task you want to solve is to find prime pairs ( or similar pattern search task ) like this : So the answer is this : Or a little more complex example for chain of primes : Answer : Pretty much like Regex work , right ? What happens is that you define some function named isPrime ( x ) and use it when you need to check if next input element is actualy prime ( so it is some sort of equality to object or object space ) What I created so farI created ObjectRegex class similar to Regex class in C # . It accepts patterns in above and execute predicate asociated with it to identify object.It works perfectly fine , but the problem is for it to work any sequence of type TValue should be converted to string before it will be passed to Regex pattern and for that I should apply ALL predicates to entire sequence . O ( n*m ) is a bad idea afterall ... .I decided to go around it the hard way and ... .try to inherit string , which is sealed and inheritance is forbidden . What is needed from this inherited class is override accessor for the benefit of deferred execution of predicates to moment when it actualy make sense.So , any idea how to make it ? I love .NET Regex and it 's syntax , is there a way to go around this string curse and deceive engine ? Reflection maybe or some hardcore I do n't know ? Update 1I found this article http : //www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-timeand think it can be done through replacement of this [ int index ] method by my code , but i think it will corrupt everything else , cause you just ca n't replace method for only one instance . <code> 1 2 3 4 5 6 7 8 9 10 11 12 13 { prime } { anyNumber } { prime } ( 3,4,5 ) ( 5,6,7 ) ( 11,12,13 ) { prime } ( { anyNumber } { prime } ) + ( 3 , ( 4,5 ) , ( 6,7 ) ) ( 11 , ( 12,13 ) ) char this [ int index ] { get ; }
How to search patterns in arbitrary sequences ?
C_sharp : I 'm trying to normalize arbitrary chains of .Skip ( ) and .Take ( ) calls to a single .Skip ( ) call followed by an optional single .Take ( ) call.Here are some examples of expected results , but I 'm not sure if these are correct : Can anyone confirm these are the correct results to be expected ? Here is the basic algorithm that I derived from the examples : Any idea how I can confirm if this is the correct algorithm ? <code> .Skip ( 5 ) = > .Skip ( 5 ) .Take ( 7 ) = > .Skip ( 0 ) .Take ( 7 ) .Skip ( 5 ) .Skip ( 7 ) = > .Skip ( 12 ) .Skip ( 5 ) .Take ( 7 ) = > .Skip ( 5 ) .Take ( 7 ) .Take ( 7 ) .Skip ( 5 ) = > .Skip ( 5 ) .Take ( 2 ) .Take ( 5 ) .Take ( 7 ) = > .Skip ( 0 ) .Take ( 5 ) .Skip ( 5 ) .Skip ( 7 ) .Skip ( 11 ) = > .Skip ( 23 ) .Skip ( 5 ) .Skip ( 7 ) .Take ( 11 ) = > .Skip ( 12 ) .Take ( 11 ) .Skip ( 5 ) .Take ( 7 ) .Skip ( 3 ) = > .Skip ( 8 ) .Take ( 4 ) .Skip ( 5 ) .Take ( 7 ) .Take ( 3 ) = > .Skip ( 5 ) .Take ( 4 ) .Take ( 11 ) .Skip ( 5 ) .Skip ( 3 ) = > .Skip ( 8 ) .Take ( 3 ) .Take ( 11 ) .Skip ( 5 ) .Take ( 7 ) = > .Skip ( 5 ) .Take ( 6 ) .Take ( 11 ) .Take ( 5 ) .Skip ( 3 ) = > .Skip ( 3 ) .Take ( 2 ) .Take ( 11 ) .Take ( 5 ) .Take ( 3 ) = > .Skip ( 0 ) .Take ( 3 ) class Foo { private int skip ; private int ? take ; public Foo Skip ( int value ) { if ( value < 0 ) value = 0 ; this.skip += value ; if ( this.take.HasValue ) this.take -= value ; return this ; } public Foo Take ( int value ) { if ( value < 0 ) value = 0 ; if ( ! this.take.HasValue || value < this.take ) this.take = value ; return this ; } }
Normalizing chains of .Skip ( ) and .Take ( ) calls
C_sharp : I was just working on some code and caught myself making this errorobviously this is wrong and should be but it just got me thinking in regards to readability would the first be easier ? Maybe having some logic that could say unless a new stringName is specified , use the first one ? Really not a question , Im just curious if there is something I dont fully comprehend on the logic behind compiling a statement like this . <code> if ( stringName == `` firstName '' || `` lastName '' ) // Do code if ( stringName == `` firstName '' || stringName == `` lastName '' ) // Do code
C # Operators and readability
C_sharp : I 've started to use a define class like so : The advantages I see is : Ensures I do n't break stuff that with an # if.. # else.. # endif would not be checked by compiler.I can do a find references to see where it is used.It 's often useful to have a bool for debug , defines code is longer/more messy.Possible disadvantage I see : Compiler ca n't optimize unused code if the Defines class is in another assembly . Which is why I have made internal.Am I missing any other disadvantages ? [ Edit ] Typical examples of usage : Or : <code> internal sealed class Defines { /// < summary > /// This constant is set to true iff the define DEBUG is set . /// < /summary > public const bool Debug = # if DEBUG true ; # else false ; # endif } private readonly Permissions _permissions = Defines.Debug ? Permissions.NewAllTrue ( ) : Permissions.NewAllFalse ( ) ; var str = string.Format ( Defines.Debug ? `` { 0 } { 1 } ( { 2 } ) '' : `` { 0 } { 1 } '' , actual , text , advance ) ;
Defines.Debug vs # if DEBUG
C_sharp : I have a method which compares two nullable ints and prints the result of the comparison to the console : And this is the result of its decompilation : The result is more or less what I expected but I wonder why the non-short-circuit version of the logical 'and ' operator ( & ) is used instead of the short-circuit version ( & & ) . It seems to me that the latter would be more efficient - if one side of the comparison is already known to be false then there is no need to evaluate the other side . Is the & operator necessary here or is this just an implementation detail that is not important enough to bother about ? <code> static void TestMethod ( int ? i1 , int ? i2 ) { Console.WriteLine ( i1 == i2 ) ; } private static void TestMethod ( int ? i1 , int ? i2 ) { int ? nullable = i1 ; int ? nullable2 = i2 ; Console.WriteLine ( ( nullable.GetValueOrDefault ( ) == nullable2.GetValueOrDefault ( ) ) & ( nullable.HasValue == nullable2.HasValue ) ) ; }
Why is the short-circuit logical 'and ' operator not used when comparing two nullables for equality ?
C_sharp : When I execute an update on my SQL Server database , I get a result of the rows affected by the update AND the affected rows of some triggers.So for example , an update executed directly on database : Now when I execute _context.Database.ExecuteSqlCommand ( query , params ) I always get the sum of all those results , in my example the result value is 35 . I only need the result of the UPDATE , in my example 32 . Is there any possibility to ignore the results of the triggers ? <code> UPDATE : ( 32 row ( s ) affected ) Trigger1 : ( 1 row ( s ) affected ) Trigger2 : ( 2 row ( s ) affected ) ...
Get only result of update query
C_sharp : While modelling my domain classes , I found that Entity Framework lets you model inheritance relationships , but does n't support promoting a base type instance to its derived type , i.e . changing an existing Person row in the database to an Employee , which derives from Person.Apparently , I was n't the first to wonder about this , because this question has been asked and answered on Stack Overflow multiple times ( e.g . see here and here ) .As indicated in these answers , Entity Framework does n't support this because this is n't allowed in Object-Oriented Programming either : once an instance is created , you can not change its run-time type.Fair enough , from a technical perspective I can understand that once a single block of memory is allocated for an object , tacking on a few extra bytes afterwards to hold the derived type 's fields in will probably require the entire memory block to be reallocated , and as a consequence , will mean that the object 's pointer has now changed , which in turn introduces even more problems . So I get that this would be difficult to implement , and therefore not supported in C # .However , aside from the technical component , the answers ( and here too , see final paragraph on page 1 ) also seem to imply that it is considered bad design when you want to change an objects run-time type , saying that you should n't need this kind of type-changing and should use composition for these situations instead.Frankly , I do n't get why - I 'd say its perfectly valid to want to work Employee instances in the same way as you would with a Person instance ( i.e . by inheriting Employee from Person ) , even if at some point in time a Person will be hired as an Employee , or an Employee quits and becomes a Person again.Conceptually , I do n't see anything wrong with this ? Can anyone explain this to me ? -- Edit , to clarify , why is this considered bad design : ... but this is n't ? <code> public class Person { public string Name { get ; set ; } } public class Employee : Person { public int EmployeeNr { get ; set ; } public decimal Salary { get ; set ; } } public class Person { public string Name { get ; set ; } public EmployeeInfo EmployeeInfo { get ; set ; } } public class EmployeeInfo { public int EmployeeNr { get ; set ; } public decimal Salary { get ; set ; } }
Inheritance : why is changing an object 's type considered bad design ?
C_sharp : It 's an asp.net core webapi project , and I simply put the [ Authorize ] attribute to protect those apis . If user is not authorized , the api will return `` 401 unauthorized '' . My question is how can I localize the `` 401 unauthorized '' message if unauthorized.For other data annotations , I can set the ErrorMessage property of the DataAnnotaion Attribute , like [ Required ( ErrorMessage = `` xxx '' ) ] . But , there 's no such property for AuthorizeAttribute.Thanks for @ Athanasios , I came up with my solution , hope it can help someone . ( ErrorMessages is just a shared class ) .Above code will return a problem details to the client . <code> using System ; using System.Threading.Tasks ; using YourNamespace.Messages ; using Microsoft.AspNetCore.Authorization ; using Microsoft.AspNetCore.Http ; using Microsoft.AspNetCore.Mvc ; using Microsoft.AspNetCore.Mvc.Filters ; using Microsoft.Extensions.DependencyInjection ; using Microsoft.Extensions.Localization ; using Microsoft.Extensions.Logging ; namespace YourNamespace.Attributes { [ AttributeUsage ( AttributeTargets.Class | AttributeTargets.Method , AllowMultiple = true , Inherited = true ) ] public class LocalizedAuthorizeAttribute : AuthorizeAttribute , IAsyncAuthorizationFilter { public string UnauthorizedErrorMessage { get ; set ; } public string ForbiddenErrorMessage { get ; set ; } public LocalizedAuthorizeAttribute ( ) { } public async Task OnAuthorizationAsync ( AuthorizationFilterContext context ) { var user = context.HttpContext.User ; var localizer = context.HttpContext.RequestServices.GetService < IStringLocalizer < ErrorMessages > > ( ) ; var logger = context.HttpContext.RequestServices.GetService < ILogger < LocalizedAuthorizeAttribute > > ( ) ; string url = $ '' { context.HttpContext.Request.Scheme } : // { context.HttpContext.Request.Host } { context.HttpContext.Request.Path } { context.HttpContext.Request.QueryString } '' ; if ( ! user.Identity.IsAuthenticated ) { logger.LogInformation ( $ '' Unauthroized access to ' { url } ' from { context.HttpContext.Connection.RemoteIpAddress.ToString ( ) } '' ) ; UnauthorizedErrorMessage = UnauthorizedErrorMessage ? ? `` Unauthorized '' ; ProblemDetails problemDetails = new ProblemDetails ( ) { Title = localizer [ UnauthorizedErrorMessage ] , Detail = localizer [ UnauthorizedErrorMessage + `` _Detail '' ] , Status = StatusCodes.Status401Unauthorized } ; context.Result = new ObjectResult ( problemDetails ) { StatusCode = StatusCodes.Status401Unauthorized , DeclaredType = problemDetails.GetType ( ) , } ; } else { ForbiddenErrorMessage = ForbiddenErrorMessage ? ? `` Forbidden '' ; var authorizeService = context.HttpContext.RequestServices.GetService < IAuthorizationService > ( ) ; if ( ! String.IsNullOrWhiteSpace ( Policy ) ) { AuthorizationResult result = await authorizeService.AuthorizeAsync ( user , Policy ) ; if ( ! result.Succeeded ) { logger.LogWarning ( $ '' Forbidden access to ' { url } ' from { context.HttpContext.Connection.RemoteIpAddress.ToString ( ) } '' ) ; ProblemDetails problemDetails = new ProblemDetails ( ) { Title = localizer [ ForbiddenErrorMessage ] , Detail = localizer [ ForbiddenErrorMessage + `` _Detail '' ] , Status = StatusCodes.Status403Forbidden } ; context.Result = new ObjectResult ( problemDetails ) { StatusCode = StatusCodes.Status403Forbidden , DeclaredType = problemDetails.GetType ( ) , } ; } } } } } }
How to localize the error message if unauthorized
C_sharp : Why c=-2always ? I have checked in loop also . Its seems garbage value but why -2 only ? <code> int a = int.MaxValue ; int b = int.MaxValue ; int c = a + b ;
Why int.Max+ int.Max = -2
C_sharp : After my last , failed , attempt at asking a question here I 'm trying a more precise question this time : What I have : A huge dataset ( finite , but I wasted days of multi-core processing time to compute it before ... ) of ISet < Point > .A list of input values between 0 to 2n , n≤17What I need:3 ) A table of [ 1 ] , [ 2 ] where I map every value of [ 2 ] to a value of [ 1 ] The processing : For this computation I have a formula , that takes a bit value ( from [ 2 ] ) and a set of positions ( from [ 1 ] ) and creates a new ISet < Point > . I need to find out which of the original set is equal to the resulting set ( i.e . The `` cell '' in the table at `` A7 '' might point to `` B '' ) .The naive way : Compute the new ISet < Point > and use .Contains ( mySet ) or something similar on the list of values from [ 1 ] . I did that in previous versions of this proof of concept/pet project and it was dead slow when I started feeding huge numbers . Yes , I used a profiler . No , this was n't the only slow part of the system , but I wasted a considerable amount of time in this naive lookup/mapping.The question , finally : Since I basically just need to remap to the input , I thought about creating a List of hashed values for the list of ISet < Point > , doing the same for my result from the processing and therefor avoiding to compare whole sets.Is this a good idea ? Would you call this premature optimization ( I know that the naive way above is too slow , but should I implement something less clever first ? Performance is really important here , think days of runtime again ) ? Any other suggestions to ease the burdon here or ideas what I should read up on ? Update : Sorry for not providing a better explanation or a sample right away.Sample for [ 1 ] ( Note : These are real possible datapoints , but obviously it 's limited ) : [ 2 ] is just a boolean vector of the length n. For n = 2 it's0,00,11,01,1I can do that one by using an int or long , basically.Now I have a function that takes an vector and an ISet < Point > and returns a new ISet < Point > . It 's not a 1:1 transformation : An set of 5 might result in a set of 11 or whatever . The resulting ISet < Point > is however guaranteed to be part of the input.Using letters for a set of points and numbers for the bit vectors , I 'm starting with thisWhat I need to have at the end isThere are several costly operations in these project , one is the preparation of the sets of point ( [ 1 ] ) . But this question is about the matching now : I can easily ( more or less , not that important now ) compute a target ISet for a given bit vector and a source ISet . Now I need to match/find that in the original set.The whole beast is going to be a state machine , where the set of points is a valid state . Later I do n't care about the individual states , I can actually refer to them by anything ( a letter , an index , whatever ) . I just need to keep the associations : 1 , B = > CUpdate : Eric asked if a HashSet would be possible . The answer is yes , but only if the dataset stays small enough . My question ( hashing ) is : Might it be possible/a good idea to employ a hashing algorithm for this hashset ? My idea is this : Walk the ( lazily generated ) list/sequence of ISet < Point > ( I could change this type , I just want to stress that it is a mathematical set of points , no duplicates ) .Create a simpler representation of the input ( a hash ? ) and store it ( in a hashset ? ) Compute all target sets for this input , but only store again a simple representation ( see above ) Discard the setFix up the mapping ( equal hash = equal state ) Good idea ? Problems with this ? One that I could come up with is a collision ( how probable is that ? ) - and I would n't know a good hashing function to begin with.. <code> new List < ISet < Point > > ( ) { new HashSet ( ) { new Point ( 0,0 ) } , new HashSet ( ) { new Point ( 0,0 ) , new Point ( 2,1 ) } , new HashSet ( ) { new Point ( 0,1 ) , new Point ( 3,1 ) } } A B C D E F1234567 A B C D E F1 - C A E - -2 B C E F A -3 ... ... ... ... ... .4 ... ... ... ... ... .5 ... ... ... ... ... .6 F C B A - - 7 E - C A - D
Improving set comparisons by hashing them ( being overly clever.. ? )
C_sharp : I 've created an Interface like so : However , when I implement the interface in a class , I have to define the CloneTo method also using T as the type as follows : This does compile and run . However , it 's not ideal as I could pass any other item that implements ICacheable to the method where I only want to be able to send an instance of the class . What I really want is to implement it more like this : That way I could only pass the proper type of entity.I tried instead creating the interface as of T , i.e.Which did then allow me to tailor the implementing class 's method to only accept that type . However , I then could no longer have a List < ICacheable > .Does anyone know if it 's possible to achieve what I 'm trying to do here ? Thanks ! <code> public interface ICacheable { void CloneTo < T > ( T entity ) where T : class , new ( ) ; } public class MyEntity : ICacheable { public void CloneTo < T > ( T genericEntity ) where T : class , new ( ) { } } public class MyEntity : ICacheable { public void CloneTo ( MyEntity entity ) { } } public interface ICacheable < T >
c # interface with method < T > but implement as concreate
C_sharp : I want to get the mac address of my software user on the network due to some security reasons . But i am able to get the mac address of the router through following method.I need the specific mac address of the system that access my software on the internet and the internal device of that router . is that possible through C # ? <code> public string GetMACAddress ( ) { NetworkInterface [ ] nics = NetworkInterface.GetAllNetworkInterfaces ( ) ; String sMacAddress = string.Empty ; foreach ( NetworkInterface adapter in nics ) { if ( sMacAddress == String.Empty ) // only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIPProperties ( ) ; sMacAddress = adapter.GetPhysicalAddress ( ) .ToString ( ) ; } } return sMacAddress ; }
In C # how to find the mac address of internal devices not the Router mac address
C_sharp : I 'm looking for the fastest way to create scaled down bitmap that honors EXIF orientation tagRef : https : //weblogs.asp.net/bleroy/the-fastest-way-to-resize-images-from-asp-net-and-it-s-more-supported-ishCurrently i use the following code to create a Bitmap that honors EXIF Orientation tagI 'm first creating a orientation fixed image , then resizing it ( preserving aspect ratio ) for fast processing.Now WIC allows much faster image manipulation.Ref : https : //stackoverflow.com/a/57987315/848968How can i create a Scaled Down BitmapImage that honours the EXIF tag Update : <code> static Bitmap FixImageOrientation ( Bitmap srce ) { const int ExifOrientationId = 0x112 ; // Read orientation tag if ( ! srce.PropertyIdList.Contains ( ExifOrientationId ) ) return srce ; var prop = srce.GetPropertyItem ( ExifOrientationId ) ; var orient = BitConverter.ToInt16 ( prop.Value , 0 ) ; // Force value to 1 prop.Value = BitConverter.GetBytes ( ( short ) 1 ) ; srce.SetPropertyItem ( prop ) ; // Rotate/flip image according to < orient > switch ( orient ) { case 1 : srce.RotateFlip ( RotateFlipType.RotateNoneFlipNone ) ; return srce ; case 2 : srce.RotateFlip ( RotateFlipType.RotateNoneFlipX ) ; return srce ; case 3 : srce.RotateFlip ( RotateFlipType.Rotate180FlipNone ) ; return srce ; case 4 : srce.RotateFlip ( RotateFlipType.Rotate180FlipX ) ; return srce ; case 5 : srce.RotateFlip ( RotateFlipType.Rotate90FlipX ) ; return srce ; case 6 : srce.RotateFlip ( RotateFlipType.Rotate90FlipNone ) ; return srce ; case 7 : srce.RotateFlip ( RotateFlipType.Rotate270FlipX ) ; return srce ; case 8 : srce.RotateFlip ( RotateFlipType.Rotate270FlipNone ) ; return srce ; default : srce.RotateFlip ( RotateFlipType.RotateNoneFlipNone ) ; return srce ; } } public static Bitmap UpdatedResizeImage ( Bitmap source , Size size ) { var scale = Math.Min ( size.Width / ( double ) source.Width , size.Height / ( double ) source.Height ) ; var bmp = new Bitmap ( ( int ) ( source.Width * scale ) , ( int ) ( source.Height * scale ) ) ; using ( var graph = Graphics.FromImage ( bmp ) ) { graph.InterpolationMode = InterpolationMode.High ; graph.CompositingQuality = CompositingQuality.HighQuality ; graph.SmoothingMode = SmoothingMode.AntiAlias ; graph.DrawImage ( source , 0 , 0 , bmp.Width , bmp.Height ) ; } return bmp ; } if ( ( bitmapMetadata ! = null ) & & ( bitmapMetadata.ContainsQuery ( `` System.Photo.Orientation '' ) ) ) { object o = bitmapMetadata.GetQuery ( `` System.Photo.Orientation '' ) ; if ( o ! = null ) { switch ( ( ushort ) o ) { case 3 : rotatedImage = new TransformedBitmap ( resized , new RotateTransform ( 180 ) ) ; break ; case 6 : rotatedImage = new TransformedBitmap ( resized , new RotateTransform ( 90 ) ) ; break ; case 8 : rotatedImage = new TransformedBitmap ( resized , new RotateTransform ( 270 ) ) ; break ; } } }
Using WIC to Quickly Create Scaled Down Bitmap that honors EXIF Orientation Tag
C_sharp : Background : In an attribute specification , there is sometimes two valid ways to write the applied attribute . For example , if an attribute class has the name HorseAttribute , you can apply the attribute as either [ HorseAttribute ] or just [ Horse ] . Ambiguities can be resolved with a @ , for example [ @ Horse ] .The following is a valid program : The C # compiler is able to pick Alpha.HorseAttribute when I write just [ Horse ] . And after all , the type Beta.Horse is entirely unsuitable for use in an attribute specification.Even if I swap the names , the C # compiler will know what to do : Again , the compiler knows I want Alpha.Horse.And now for the code I want to ask about . It is identical to the above , except that the two types now have the same name : Now , the C # -compiler refuses to build , saying : error CS0104 : 'Horse ' is an ambiguous reference between 'Alpha.Horse ' and 'Beta.Horse'Try it online ! My question is , why can the compiler not pick the right one in this case , when it did it nicely in the two examples earlier ? Is this behavior in accordance with the C # Language Specification ? Is it actually required that the C # compiler issues an error here ? ( Of course I know I can resolve it by saying [ Alpha.Horse ] explicitly , so I am not asking for that `` solution '' . ) <code> using System ; using Alpha ; using Beta ; namespace N { [ Horse ] class C { } } namespace Alpha { // valid non-abstract attribute type with accessible constructor class HorseAttribute : Attribute { } } namespace Beta { // any non-attribute type with that name enum Horse { } } using System ; using Alpha ; using Beta ; namespace N { [ Horse ] class C { } } namespace Alpha { // valid non-abstract attribute type with accessible constructor class Horse : Attribute { } } namespace Beta { // any non-attribute type with that name enum HorseAttribute { } } using System ; using Alpha ; using Beta ; namespace N { [ Horse ] class C { } } namespace Alpha { // valid non-abstract attribute type with accessible constructor class Horse : Attribute { } } namespace Beta { // any non-attribute type with that name enum Horse { } }
Curious ambiguity in attribute specification ( two using directives )
C_sharp : Using C # and Regex I have a strange situation : In my world the above would give me a result in 'collection ' that contains 6 results . Strangly enough my collection contains 12 results and every second result is { } ( empty ) .I have tried rewriting it to : But it gives me the exact same result . What am I missing here ? I am using .Net framework 4.5 , C # <code> string substr = `` 9074552545,9075420530,9075662235,9075662236,9075952311,9076246645 '' ; MatchCollection collection = Regex.Matches ( substr , @ '' [ \d ] * '' ) ; string substr = `` 9074552545,9075420530,9075662235,9075662236,9075952311,9076246645 '' ; Regex regex = new Regex ( @ '' [ \d ] * '' ) ; MatchCollection collection = regex.Matches ( substr ) ;
Regex MatchCollection gets too many results
C_sharp : C # ensures that certain types always have atomic reads and writes . Do I have those same assurances when calling Array.Copy on two arrays of those types ? Is each element atomically read and written ? I browsed some of the source code but did not come away with a solid answer.For example , if I rolled my own code for copying two arrays ... ... and called the Copy < int > variant , this guarantees that each element is atomically read from source and atomically written to destination because C # promises that int reads and writes are atomic . I 'm simply asking if Array.Copy maintains that guarantee ( as opposed to , say , using its own specialized memory block copy routine that possibly breaks this guarantee ) . <code> static void Copy < T > ( T [ ] source , T [ ] destination , int length ) { for ( int i = 0 ; i < length ; ++i ) destination [ i ] = source [ i ] ; }
Does Array.Copy maintain the guarantee about atomic reads and writes on a per element basis ?
C_sharp : I have two interfaces with same method and in my main class The compiler doesnt give any error and the result is displayed..Is it right ? ? should n't we use FirstInterface.add ? ? does it mean interfaces are resolved at compile time ? ? <code> interface FirstInterface { int add ( int x , int y ) ; } interface SecondInterface { int add ( int x , int y ) ; } class TestInterface : FirstInterface , SecondInterface { public TestInterface ( ) { } public int add ( int x , int y ) { return x + y ; } } static void Main ( string [ ] args ) { TestInterface t = new TestInterface ( ) ; int result = t.add ( 3 , 4 ) ; }
Multiple Interface inheritance in C #
C_sharp : I have aproblem with the order of static variable declaration in C # When i run this code : The output is : But when i change the static variable declaration order like this : The Output is : Why this happend ? <code> static class Program { private static int v1 = 15 ; private static int v2 = v1 ; static void Main ( string [ ] args ) { Console.WriteLine ( `` v2 = `` +v2 ) ; } } v2=15 static class Program { private static int v2 = v1 ; private static int v1 = 15 ; static void Main ( string [ ] args ) { Console.WriteLine ( `` v2 = `` +v2 ) ; } } v2 = 0
Static variable order
C_sharp : I have this if else statement which is assigned to compare results from a text box to a list of context . I am wondering how do i make it such that it is case insensitive ? <code> value = textbox1.Text ; if ( article.contains ( value ) ) { label = qwerty ; } else { break ; {
c # If else statement with case insensative
C_sharp : I have an ObservableCollection which is the DataContext for a Grid . The Grid is a User Control inserted into the main Window.I would like to display 'Record x of y ' in the StatusBar so , as a first step , I am attempting to display it in the Grid using this XAML : The Count works without issue , and updates automatically as new items are added . The CurrentPosition , which is defined in my code below , stays at 0 constantly.How can I cause the CurrentPosition to update automatically ? I am hoping not to have to use INotify** because this is already an ObservableCollection.I also do not have any code-behind , so I hope it is achievable within my class ( or model ) and the XAML.I did attempt to work with CurrentChanged but without success : MyObservableCollection : Update : I 'm adding the following code as a possible solution , but I do n't really like it and I 'm hoping a better one comes along that does n't require me to use INotifyPropertyChanged - I suspect I 'll end repeating all the functionality that should already be available with an ObservableCollection . ( I also do n't know why I need to re-notify of the Count changing . ) Update 2 : The following is not a ( full ) solution as it interferes with other behaviours ( notifications ) of the collection , but I 've kept it here in-case it contains any useful information.With this I can display `` Item 1 of 3 '' in the Grid : I no longer need this TextBlock though , as I can refer to the DataContext properties directly in the ( main ) StatusBar : PROBLEM AND SOLUTIONFollowing @ JMarsch 's answer : Naming my property CurrentPosition is masking the property of the same name that is already available directly from the DataContext , because the binding is to the collection 's default view ( which has this property ) .The solution is either to rename to MyCurrentPosition , and refer to the original property from the StatusBar or , as I did , to remove my version of this property ( and of GetDefaultView ) altogether : they are n't doing anything particularly useful.I then use the following simple ValueConverter to convert 0,1,2 , .. to 1,2,3 , .. in the StatusBar.StatusBar : <code> < TextBlock Grid.Row= '' 2 '' Grid.Column= '' 3 '' > < TextBlock Text= '' { Binding CurrentPosition } '' / > < TextBlock Text= '' { Binding Count } '' / > < /TextBlock > public MyObservableCollection ( ) : base ( ) { this.GetDefaultView ( ) .CurrentChanged += MyObservableCollection_CurrentChanged ; } using System ; using System.Collections.Generic ; using System.Collections.ObjectModel ; namespace ToDoApplication.Models { public class MyObservableCollection < T > : ObservableCollection < T > { public MyObservableCollection ( ) : base ( ) { } public MyObservableCollection ( List < T > list ) : base ( list ) { } public MyObservableCollection ( IEnumerable < T > collection ) : base ( collection ) { } private System.ComponentModel.ICollectionView GetDefaultView ( ) { return System.Windows.Data.CollectionViewSource.GetDefaultView ( this ) ; } public int CurrentPosition { get { return this.GetDefaultView ( ) .CurrentPosition ; } } public void MoveFirst ( ) { this.GetDefaultView ( ) .MoveCurrentToFirst ( ) ; } public void MovePrevious ( ) { this.GetDefaultView ( ) .MoveCurrentToPrevious ( ) ; } public void MoveNext ( ) { this.GetDefaultView ( ) .MoveCurrentToNext ( ) ; } public void MoveLast ( ) { this.GetDefaultView ( ) .MoveCurrentToLast ( ) ; } public bool CanMoveBack ( ) { return this.CurrentPosition > 0 ; } public bool CanMoveForward ( ) { return ( this.Count > 0 ) & & ( this.CurrentPosition < this.Count - 1 ) ; } } public enum Navigation { First , Previous , Next , Last , Add } } namespace ToDoApplication.Models { public class MyObservableCollection < T > : ObservableCollection < T > , INotifyPropertyChanged { public new event PropertyChangedEventHandler PropertyChanged ; private int _currentPos = 1 ; public MyObservableCollection ( ) : base ( ) { this.GetDefaultView ( ) .CurrentChanged += MyObservableCollection_CurrentChanged ; this.CollectionChanged += MyObservableCollection_CollectionChanged ; } public MyObservableCollection ( List < T > list ) : base ( list ) { this.GetDefaultView ( ) .CurrentChanged += MyObservableCollection_CurrentChanged ; this.CollectionChanged += MyObservableCollection_CollectionChanged ; } public MyObservableCollection ( IEnumerable < T > collection ) : base ( collection ) { this.GetDefaultView ( ) .CurrentChanged += MyObservableCollection_CurrentChanged ; this.CollectionChanged += MyObservableCollection_CollectionChanged ; } void MyObservableCollection_CurrentChanged ( object sender , EventArgs e ) { this.CurrentPosition = this.GetDefaultView ( ) .CurrentPosition ; } void MyObservableCollection_CollectionChanged ( object sender , System.Collections.Specialized.NotifyCollectionChangedEventArgs e ) { RaisePropertyChanged ( `` Count '' ) ; } private System.ComponentModel.ICollectionView GetDefaultView ( ) { return System.Windows.Data.CollectionViewSource.GetDefaultView ( this ) ; } public int CurrentPosition { get { return _currentPos ; } private set { if ( _currentPos == value + 1 ) return ; _currentPos = value + 1 ; RaisePropertyChanged ( `` CurrentPosition '' ) ; } } private void RaisePropertyChanged ( string propertyName ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public void MoveFirst ( ) { this.GetDefaultView ( ) .MoveCurrentToFirst ( ) ; } public void MovePrevious ( ) { this.GetDefaultView ( ) .MoveCurrentToPrevious ( ) ; } public void MoveNext ( ) { this.GetDefaultView ( ) .MoveCurrentToNext ( ) ; } public void MoveLast ( ) { this.GetDefaultView ( ) .MoveCurrentToLast ( ) ; } public bool CanMoveBack ( ) { return this.CurrentPosition > 1 ; } public bool CanMoveForward ( ) { return ( this.Count > 0 ) & & ( this.CurrentPosition < this.Count ) ; } } public enum Navigation { First , Previous , Next , Last , Add } } < TextBlock Grid.Row= '' 2 '' Grid.Column= '' 3 '' x : Name= '' txtItemOf '' > Item < TextBlock x : Name= '' txtItem '' Text= '' { Binding CurrentPosition } '' / > of < TextBlock x : Name= '' txtOf '' Text= '' { Binding Count } '' / > < /TextBlock > < StatusBar DockPanel.Dock= '' Bottom '' > Item < TextBlock Text= '' { Binding ElementName=vwToDo , Path=DataContext.CurrentPosition } '' / > Of < TextBlock Text= '' { Binding ElementName=vwToDo , Path=DataContext.Count } '' / > < /StatusBar > [ ValueConversion ( typeof ( int ) , typeof ( int ) ) ] class PositionConverter : IValueConverter { public object Convert ( object value , Type targetType , object parameter , System.Globalization.CultureInfo culture ) { return ( int ) value + 1 ; } public object ConvertBack ( object value , Type targetType , object parameter , System.Globalization.CultureInfo culture ) { return ( int ) value - 1 ; } } < StatusBar DockPanel.Dock= '' Bottom '' x : Name= '' status '' > Item < TextBlock Text= '' { Binding ElementName=vwToDo , Path=DataContext.CurrentPosition , Converter= { StaticResource posConverter } } '' / > Of < TextBlock Text= '' { Binding ElementName=vwToDo , Path=DataContext.Count } '' / > < /StatusBar >
StatusBar record x of y
C_sharp : I 'm using a RIA Services DomainContext in a Silverlight 4 app to load data . If I 'm using the context from the UI thread , is the callback always going to be on the UI thread ? Or put another way , is the callback always on the same thread as the call ? Some example code below illustrating the scenario ... <code> private void LoadStuff ( ) { MyDomainContext context = new MyDomainContext ( ) ; context.Load ( context.GetStuffQuery ( ) , op = > { if ( ! op.HasError ) { // Use data . // Which thread am I on ? } else { op.MarkErrorAsHandled ( ) ; // Do error handling } } , null ) ; }
Which thread is the callback executing on when performing an asynchronous RIA Services call ?
C_sharp : I 'm getting an error incorrect syntax near the keyword WHEREwith the following SQL statement : What 's wrong ? <code> SqlCommand scInsertCostSpilt = new SqlCommand ( `` INSERT INTO [ ASSETS_CC ] ( [ DEPT ] , [ CC ] , [ PER_CENT ] ) WHERE [ ASSET_NO ] = @ AssetNumber ) '' + '' Values ( @ AssetNumber , @ Dept , @ CC , @ PerCent ) '' , DataAccess.AssetConnection ) ;
SQL query : Incorrect Syntax error
C_sharp : I have a list which is declared below , at the start I default the list items to { -1 , - } . please note that throughout the program the list size is fixed at 2.My question is regarding , what would be the best approach if I need to overwrite the two values in the list.Approach 1 : Approach 2 : What would be a better approach ? With the second approach , even though I am sure there are 2 values set initially , I can run a risk of the Argument index out of range exception . But the first approach might eat more memory ( correct me if I am wrong ! ) since I am creating a new list every time.Is there a simpler , and/or better solution <code> List < int > list = new List < int > ( new int [ ] { -1 , -1 } ) ; int x = GetXValue ( ) ; int y = GetYValue ( ) ; list = new List < int > ( new int [ ] { x , y } ) ; list [ 0 ] = x ; list [ 1 ] = y ;
.NET List best approach
C_sharp : Out of curiosity I wanted to test the number of ticks to compare a GenericList against an ArrayList.And for the below code when I check the stopwatches , ArrayList seems to faster.Do I make something wrong or is there an explanation for this ? ( I believed List sto be much faster ) Tesing Code and the output below : <code> private static void ArrayListVsGenericList ( ) { // Measure for ArrayList Stopwatch w0 = new Stopwatch ( ) ; w0.Start ( ) ; ArrayList aList = new ArrayList ( ) ; for ( int i = 0 ; i < 1001 ; i++ ) { Point p = new Point ( ) ; p.X = p.Y = i ; aList.Add ( p ) ; } foreach ( Point point in aList ) { int v0 = ( ( Point ) aList [ 8 ] ) .X ; //unboxing } w0.Stop ( ) ; // Measure for Generic List < Point > Stopwatch w1 = new Stopwatch ( ) ; w1.Start ( ) ; List < Point > list = new List < Point > ( ) ; for ( int i = 0 ; i < 1001 ; i++ ) { Point p = new Point ( ) ; p.X = p.Y = i ; list.Add ( p ) ; } foreach ( var point in list ) { int v1 = list [ 8 ] .X ; } w1.Stop ( ) ; Console.WriteLine ( `` Watch 0 : `` + w0.ElapsedTicks ) ; Console.WriteLine ( `` Watch 1 : `` + w1.ElapsedTicks ) ; Console.WriteLine ( `` Watch 0 > Watch 1 : `` + ( w0.ElapsedTicks > w1.ElapsedTicks ) ) ; }
Why does a simple List < T > seem to be slower than an ArrayList ?
C_sharp : I have a struct TimePoint which is similar to a Point except , the x value is a datetime , an observable collection of these timepoints and a method that takes a datetime and returns a double value.I want to retrieve the max and min value of the doubles that are returned from the datetimesin this collection.I am new to linq and am unable to figure out the query I would have to pass on the observable collection to achieve this.Here 's what I am trying to get : How can I achieve this using LINQ ? Or is LINQ not ideal for this ? <code> double minDouble = 0 ; double maxDouble = 0 ; foreach ( TimePoint item in obsColl ) { var doubleVal = ConvertToDouble ( item.X ) ; //Here x is a datetime if ( minDouble > doubleVal ) minDouble = doubleVal ; if ( maxDouble < doubleVal ) maxDouble = doubleVal ; }
LINQ - C # - Using lambda - Get a set of data from a Collection
C_sharp : Given : Why can I write : But not : Which gives me the following warning : Error 29 Can not implicitly convert type 'MyApp.MyNS.MyStruct [ ] ' to 'System.Collections.Generic.IEnumerable < MyApp.MyNS.IMyInterface > 'And must instead be written : <code> public interface IMyInterface { } public class MyClass : IMyInterface { public MyClass ( ) { } } public struct MyStruct : IMyInterface { private int _myField ; public MyStruct ( int myField ) { _myField = myField ; } } IEnumerable < IMyInterface > myClassImps = new [ ] { new MyClass ( ) , new MyClass ( ) , new MyClass ( ) } ; IEnumerable < IMyInterface > myStructImps = new [ ] { new MyStruct ( 0 ) , new MyStruct ( 1 ) , new MyStruct ( 2 ) } ; IEnumerable < IMyInterface > myStructImps = new IMyInterface [ ] { new MyStruct ( 0 ) , new MyStruct ( 1 ) , new MyStruct ( 2 ) } ;
IEnumerable < IMyInterface > Implicitly From Class [ ] But Not From Struct [ ] . Why ?
C_sharp : Given this `` IHandle '' interface and two classes to be handled : I want to create a generic base that takes care of `` resetting '' as well as managing M1 instances : This does not compile since the compiler believes T could be `` MReset '' so it outputs : error CS0695 : 'HandlerBase ' can not implement both 'IHandle ' and 'IHandle ' because they may unify for some type parameter substitutionsThat in itself is slightly odd since I can not see how T could possibly be of type MReset since it must be of type M1 . But okay , I can accept that the compiler is smarter than me : - ) Edit : The compiler is not smarter than me : - ) According to a comment on Why does this result in CS0695 ? we have `` Constraint declarations are not considered when determining all possible constructed types '' .Now I swap the interface declarations : And suddenly I get a different error message stating that I can not implement IHandle.Handle ( MReset m ) since the class declaration does not state that it is implementing that interface : error CS0540 : 'HandlerBase.IHandle < ... > .Handle ( MReset ) ' : containing type does not implement interface 'IHandle'Question : why does the order of declarations make such a difference ? What is going wrong in the second example ? In the end it turns out that there is a solution : But the solution only works if HandlerBase implements IHandle < MReset > - not if the generic interface IHandle < T > is implemented in HandlerBase first . Why ? Edit : Implementing IHandle < T > in HandlerBase does work ( and if I had shown the code someone might have seen it ) . This works : Unfortunately my second class declaration was this : Notice the subtle difference in the location of where T : M1 : - ) The last example declares that T must implement IHandle < MReset > ( in addition to M1 ) . Duh ! <code> interface IHandle < T > { void Handle ( T m ) ; } class M1 { public int Id ; } class MReset { } class HandlerBase < T > : IHandle < MReset > , IHandle < T > where T : M1 { protected int Count ; void IHandle < T > .Handle ( T m ) { ++Count ; Console.WriteLine ( `` { 0 } : Count = { 0 } '' , m.Id , Count ) ; } void IHandle < MReset > .Handle ( MReset m ) { Count = 0 ; } } class HandlerBase < T > : IHandle < T > where T : M1 , IHandle < MReset > { ... same as before .. } class HandlerBase : IHandle < MReset > { protected int Count ; void IHandle < MReset > .Handle ( MReset m ) { Count = 0 ; } } class Handler < T > : HandlerBase , IHandle < T > where T : M1 { void IHandle < T > .Handle ( T m ) { ++Count ; Console.WriteLine ( `` { 0 } : Count = { 0 } '' , m.Id , Count ) ; } } class HandlerBase < T > : IHandle < T > where T : M1 { protected int Count ; void IHandle < T > .Handle ( T m ) { ++Count ; Console.WriteLine ( `` Type = { 0 } , Id = { 1 } , Count = { 2 } '' , GetType ( ) , m.Id , Count ) ; } } class Handler < T > : HandlerBase < T > , IHandle < MReset > where T : M1 { void IHandle < MReset > .Handle ( MReset m ) { Count = 0 ; Console.WriteLine ( `` RESET '' ) ; } } class Handler < T > : HandlerBase < T > where T : M1 , IHandle < MReset > { void IHandle < MReset > .Handle ( MReset m ) { Count = 0 ; Console.WriteLine ( `` RESET '' ) ; } }
Odd C # behavior when implementing generic interface
C_sharp : Possible Duplicate : C # okay with comparing value types to null Why does C # allow : Resharper says `` expression is always false '' - which is obviously - true since MyInt is int and not int ? But how C # allow this to compile ? The property will always be there and its type is int ! <code> class MyClass { public int MyInt ; } static void Main ( string [ ] args ) { MyClass m = new MyClass ( ) ; if ( m.MyInt == null ) // < -- -- -- -- -- -- - ? Console.Write ( `` ... ... '' ) ; }
Why does c # allow this ? ( null checking to int )
C_sharp : Checking in C # a VB.NET object for null gives unexpected compile error : Resharper 's suggested fix : I have a colleague that have done this in a year without any problems . My colleague is using Visual Studio 2012 and I 'm using Visual Studio 2013.Could it be some kind of a settings ? Why is basePackage ! = null an object ? I know VB.NET has Nothing where C # has null.UPDATE : BasePackage 's inherited this from another class : I do n't know if that 's helps in any ways.SOLUTION : When I outcomment these two operators C # is working fine again.Final Solution Added type in VB.NET . No need for C # cast then . <code> // Can not compile : var basePackage = BasePackage.GetFromID ( id ) ; // GetFromID is from VB.NETif ( basePackage ! = null ) // Errormesage : `` Can not implicitly convert 'object ' to 'bool ' { } // Can compileif ( ( bool ) ( basePackage ! = null ) ) { linkedGroups = basePackage.GetLinkedGroups ( ) ; } Public Shared Operator = ( [ object ] As CMSObject , type As System.Type ) Return [ object ] .GetType Is typeEnd OperatorPublic Shared Operator < > ( [ object ] As CMSObject , type As System.Type ) Return [ object ] .GetType IsNot typeEnd OperatorPublic Shared Operator = ( [ object ] As CMSObject , o As Object ) Return [ object ] .GetType Is oEnd OperatorPublic Shared Operator < > ( [ object ] As CMSObject , o As Object ) Return [ object ] .GetType IsNot oEnd Operator Public Shared Operator = ( [ object ] As CMSObject , type As System.Type ) Return [ object ] .GetType Is typeEnd Operator'Public Shared Operator < > ( [ object ] As CMSObject , type As System.Type ) ' Return [ object ] .GetType IsNot type'End OperatorPublic Shared Operator = ( [ object ] As CMSObject , o As Object ) Return [ object ] .GetType Is oEnd Operator'Public Shared Operator < > ( [ object ] As CMSObject , o As Object ) ' Return [ object ] .GetType IsNot o'End Operator Public Shared Operator = ( [ object ] As CMSObject , type As System.Type ) **As Boolean** Return [ object ] .GetType Is typeEnd OperatorPublic Shared Operator < > ( [ object ] As CMSObject , type As System.Type ) **As Boolean** Return [ object ] .GetType IsNot typeEnd OperatorPublic Shared Operator = ( [ object ] As CMSObject , o As Object ) **As Boolean** Return [ object ] .GetType Is oEnd OperatorPublic Shared Operator < > ( [ object ] As CMSObject , o As Object ) **As Boolean** Return [ object ] .GetType IsNot oEnd Operator
Checking in C # a VB.NET object for null gives unexpected compile error
C_sharp : When I tried a sample expression in C # in Visual StudioWhen I keep the expression 10/2 == 5 , the vs.net automatically throws a warning `` Unreachable Code Detected '' .If I change the expression 10/2 == 6 , the IDE is happy ? How does it happen ? Edited : Sorry for the incomplete question . It happens so instantly and happens even before compiling the code ? I have upvoted each of the replies and accepted the first answer on FIFO basis <code> public int Test ( ) { if ( 10/2 == 5 ) throw new Exception ( ) ; return 0 ; }
Evaluation of C # constant expression by VS.NET 2010
C_sharp : Is there a way to tell ReSharper to use the String and Int64 type names when a field or method is used on the type ( 'static-ally ' ) , but string and long for variable initialization ? Examples : <code> string name = `` @ user '' ; // butint compResult = String.Compare ( a , b , ... ) ; long x = 0 ; // butlong x = Int64.Parse ( s ) ;
ReSharper Code Cleanup
C_sharp : Ok - I have someone I work with who has written somthing like thisI dont like this ! ! If there are ten different boolean flags how many combinations are there ? 10 factorial ? I am trying to explain why this is bad <code> if ( ) if ( ) if ( ) if ( ) if ( )
How Many Combinations In This If Statement
C_sharp : I would like to know what are the differences between those two linq statements ? What is faster ? Are they the same ? What is the difference between this statementand this statement ? Thanks in advance guys.EDIT : In context of LINQ to Objects <code> from c in categoriesfrom p in productswhere c.cid == p.pidselect new { c.cname , p.pname } ; from c in categoriesjoin p in products on c.cid equals p.pidselect new { c.cname , p.pname } ;
Linq To Objects - Under The Hood Of Joins
C_sharp : In my extension that I am writing for Visual Studio 2015 I want to change the tab size and indent size as at work we have a different setting as when I am developing for opensource project ( company history dating our C period ) . I have written the following code in my command class : When testing in an experimental hive it changes it when you step through the method but when you open the Options dialog it stays the original values . When you debug again the values stay the original.What did I forget or did wrong ? <code> private const string CollectionPath = @ '' Text Editor\CSharp '' ; private void MenuItemCallback ( object sender , EventArgs e ) { var settingsManager = new ShellSettingsManager ( ServiceProvider ) ; var settingsStore = settingsManager.GetWritableSettingsStore ( SettingsScope.UserSettings ) ; var tabSize = settingsStore.GetInt32 ( CollectionPath , `` Tab Size '' , -1 ) ; var indentSize = settingsStore.GetInt32 ( CollectionPath , `` Indent Size '' , -1 ) ; if ( tabSize ! = -1 & & indentSize ! = -1 ) { settingsStore.SetInt32 ( CollectionPath , `` Tab Size '' , 2 ) ; settingsStore.SetInt32 ( CollectionPath , `` Indent Size '' , 2 ) ; } }
Writing Visual Studio settings in an extension do not stay
C_sharp : Consider the following XamlIt will set theText Property of a TextBox ( only WPF ) Content Property of a ButtonChildren Property of a GridBut how is this specified ? How do you specify which Property that goes between the opening and closing tag in Xaml ? Is this set by some metadata in the Dependency Property or what ? Thanks <code> < Grid > < TextBox > Text < /TextBox > < Button > Content < /Button > < /Grid >
Specify which Property goes between the opening and closing tag in Xaml
C_sharp : I have a SOAP web service which I am pulling various information from . Most functions are working correctly , but I need some functions to return a List.The WebMethod is defined like : The web service is referenced in the main project and is called by : client_GetAllMyTypesCompleted is defined as : It is here that the TargetInvocationException is thrown , specifically regarding Result . If you run the web service by itself the correct data is returned . For reference GLS_DataQuery is defined as : So why am I seeing this error ? Or how should I be returning a list of objects in this instance ? It might be of relevance that the web service is hosted in Azure.EDIT : Attaching the debugger to the instance of the web service running in Azure sees that it does return the correct data . The error is thrown in a Xamarin phone app that is calling the web service . The `` Message '' of the error is simply a null reference error and the stack trace is : at MyApp.MyService.Service1SoapClient.EndGetAllMyTypes ( IAsyncResult result ) at MyApp.MyService.Service1SoapClient.OnEndGetAllMyTypes ( IAsyncResult result ) at System.ServiceModel.ClientBase ` 1.OnAsyncCallCompleted ( IAsyncResult result ) <code> List < MyType > myTypes = new List < MyTypes > ( ) ; [ WebMethod ] public List < MyType > GetAllMyTypes ( ) { string sql = `` SELECT * FROM MyType '' ; DataTable dt = new DataTable ( ) ; dt = Globals.GLS_DataQuery ( sql ) ; List < MyType > myType = new List < MyType > ( ) ; foreach ( DataRow row in dt.Rows ) { MyType myType = new MyType ( ) { ID = ( int ) row [ `` Id '' ] } ; myTypes.Add ( myType ) ; } return myTypes ; } client.GetAllMyTypesCompleted += client_GetAllMyTypesCompleted ; client.GetAllMyTypesAsync ( ) ; private void client_GetAllMyTypesCompleted ( object sender , GetAllMyTypesCompletedEventArgs e ) { var collection = e.Result ; } public static DataTable GLS_DataQuery ( string sql ) { DataTable dt = new DataTable SqlCommand command = new SqlCommand ( sql , connection ) ; SqlDataAdapter adapter = new SqlDataAdapter ( command ) ; adapter.Fill ( dt ) ; return dt ; }
TargetInvocationException when retrieving list from SOAP web service in Azure
C_sharp : Noticed MongoDB has different keywords , like InsertOne , ReplaceOne , etc.A point of Linq ( Language Integrated Query ) , was to have a universal language where people can utilize dependency injection and swap between SQL or NoSQL without changing syntax heavily . SQL uses .Add ( ) and Remove ( ) .Is there an easy way to make the two have similar syntax ? SQL : https : //docs.microsoft.com/en-us/ef/core/saving/basicMongoDB : https : //docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app ? view=aspnetcore-2.2 & tabs=visual-studiohttps : //docs.mongodb.com/manual/reference/method/db.collection.insertOne/ <code> public BookService ( IConfiguration config ) { var client = new MongoClient ( config.GetConnectionString ( `` BookstoreDb '' ) ) ; var database = client.GetDatabase ( `` BookstoreDb '' ) ; _books = database.GetCollection < Book > ( `` Books '' ) ; } public List < Book > Get ( ) { return _books.Find ( book = > true ) .ToList ( ) ; } public Book Get ( string id ) { return _books.Find < Book > ( book = > book.Id == id ) .FirstOrDefault ( ) ; } public Book Create ( Book book ) { _books.InsertOne ( book ) ; return book ; } public void Update ( string id , Book bookIn ) { _books.ReplaceOne ( book = > book.Id == id , bookIn ) ; } public void Remove ( Book bookIn ) { _books.DeleteOne ( book = > book.Id == bookIn.Id ) ; } public void Remove ( string id ) { _books.DeleteOne ( book = > book.Id == id ) ; } }
Use Same Syntax for MongoDB and SQL with C # or Linq
C_sharp : I am using WebClient to try and get a string response from a piece of hardware connected locally to my PC . My PC has a network adaptor connected to a LAN and a second adaptor that is connected only to my piece of hardware.If I use IE with the URL : http : //169.254.103.127/set.cmd ? user=admin+pass=12345678+cmd=getpower I get back a string in response . I am trying to use the following code snippet to acheive the same thing : This snippet works if I disable my network adaptor that is connected to my LAN , but times out otherwise.Can someone explain why this is happening and what I need to do to route the request to the correct network ? <code> using ( WebClient client = new WebClient ( ) ) { client.Proxy = WebRequest.DefaultWebProxy ; client.Credentials = CredentialCache.DefaultCredentials ; client.Proxy.Credentials = CredentialCache.DefaultCredentials ; client.Headers [ `` User-Agent '' ] = `` Mozilla/4.0 ( Compatible ; Windows NT 5.1 ; MSIE 6.0 ) `` + `` ( compatible ; MSIE 6.0 ; Windows NT 5.1 ; `` + `` .NET CLR 1.1.4322 ; .NET CLR 2.0.50727 ) '' ; String test = client.DownloadString ( @ '' http : //169.254.103.127/set.cmd ? user=admin+pass=12345678+cmd=getpower '' ) ; }
WebClient and multiple network adaptors
C_sharp : I 'm trying to automate some stuff on a legacy application that I do n't have the source to . So I 'm essentially trying to use the Windows API to click the buttons I 'll need on it.There is a toolbar of type msvb_lib_toolbar that looks like this : I can get a handle to it ( I think ) by using this code : Looking at the docs , it seems I should be able to use SendMessage and the TB_PRESSBUTTON message to click these buttons : However , I 'm not sure how to go about setting the wParam and lParam to click the wanted button on the bar . The documentation does n't seem to be helping much either.Could you please advise ? Based on comments , I 've also tried UIAutomation . I can locate the toolbar using the following code : But from here , I 'm not sure what to do as Spy++ shows no further children of this object : Loking at the Current property of this AutomationElement I ca n't seen anything jumping out at me but the BoundingRectangle does seem to indicate that I 've found the right element.Using inspector.exe also does n't indicate any children on the toolbar . <code> IntPtr window = FindWindow ( `` ThunderRT6FormDC '' , `` redacted '' ) ; IntPtr bar = FindWindowEx ( window , IntPtr.Zero , '' msvb_lib_toolbar '' , null ) ; [ DllImport ( `` user32.dll '' ) ] public static extern int SendMessage ( int hWnd , uint Msg , int wParam , int lParam ) ; AutomationElement mainWindow = AutomationElement.RootElement.FindFirst ( TreeScope.Children , new PropertyCondition ( AutomationElement.NameProperty , `` Migration Expert '' ) ) ; AutomationElement toolbar = mainWindow.FindFirst ( TreeScope.Subtree , new PropertyCondition ( AutomationElement.ClassNameProperty , `` msvb_lib_toolbar '' ) ) ;
Click Button in Toolbar of Other Program
C_sharp : For me it looks quite strange , and like a bug.This code in Release mode in Visual Studio 2019 provides infinite loop.volatile or Thread.MemoryBarrier ( ) ; ( after _a = 0 ; ) solves the issue . Do n't think I had such issue with VS2015 . Is this correct behavior ? What exact part is optimized ? <code> class Program { private static int _a ; static void Main ( string [ ] args ) { _a = 1 ; while ( _a == 1 ) { Console.WriteLine ( _a ) ; _a = 0 ; } } }
VS 2019 optimize code in release mode broken ?
C_sharp : I 've built an event system that maintains a dictionary of delegates , adds/removes elements to this dictionary via generic Subscribe/Unsubscribe methods ( which each take an Action of type T ) , and has a Publish method to notify the subscribers when something happens ( which also takes an Action of type T ) . Everything works fine , but I 've noticed I can not use += or -= when adding or removing elements to my dictionary , as the types passed into the methods ( Action of T ) , do not match the types stored in the dictionary ( Delegate ) . The following snippet shows what I can and can not do.I mostly understand Jon Skeet 's answer here += operator for Delegate specifically , this partThe binary + operator performs delegate combination when both operands are of some delegate type D. ( If the operands have different delegate types , a binding-time error occurs . ) What I do n't understand , is thisThe compiler turns it into a call to Delegate.Combine . The reverse operation , using - or -= , uses Delegate.Remove.What exactly is going on when I use += or -= , versus Delegate.Combine ? What are the differences between the two , making one implementation valid , and another invalid ? <code> private readonly Dictionary < Type , Delegate > delegates = new Dictionary < Type , Delegate > ( ) ; public void Subscribe < T > ( Action < T > del ) { if ( delegates.ContainsKey ( typeof ( T ) ) ) { // This does n't work ! delegates [ typeof ( T ) ] += del as Delegate ; // This does n't work ! delegates [ typeof ( T ) ] += del ; // This is ok delegates [ typeof ( T ) ] = ( Action < T > ) delegates [ typeof ( T ) ] + del ; // This is ok var newDel = ( Action < T > ) delegates [ typeof ( T ) ] + del ; delegates [ typeof ( T ) ] = newDel ; // This is ok del += ( Action < T > ) delegates [ typeof ( T ) ] ; delegates [ typeof ( T ) ] = del ; // This is ok delegates [ typeof ( T ) ] = Delegate.Combine ( delegates [ typeof ( T ) ] , del ) ; } else { delegates [ typeof ( T ) ] = del ; } }
The difference between += and Delegate.Combine
C_sharp : Previously I have asked a question that was answered not fully , hence I have decided to re-formulate my question to understand what is going on : Here is my class hierarchy : Here is the execution code : As it is right now , it will either output A or C. It wo n't output B . Here is the question : Could you please explain how the decision is made what function to call by covering these steps ? When the decision is made what function to call - runtime or compile time ? What is the mechanism how to decide what function to call ? <code> interface I { void f ( ) ; } class A : I { // non virtual method public void f ( ) { Debug.Log ( `` -- -- > > A `` ) ; } } class B : A { // non overriding but hiding class A method public void f ( ) { Debug.Log ( `` -- -- > > B `` ) ; } } class C : I { // non virtual method public void f ( ) { Debug.Log ( `` -- -- > > C `` ) ; } } Random rnd = new Random ( ) ; var randomI = rnd.Next ( 0 , 2 ) ; I i = null ; if ( randomI == 0 ) { i = new B ( ) ; } else { i = new C ( ) ; } i.f ( ) ;
What function will be called ?
C_sharp : I have read a couple of articles about the using statement to try and understand when it should be used . It sound like most people reckon it should be used as much as possible as it guarantees disposal of unused objects.Problem is that all the examples always show something like this : That makes sense , but it 's such a small piece of code . What should I do when executing a query on a database ? What are all the steps ? Will it look something like this : What I want to know is : • Is it okay to have 4 , 5 , 10 nested using statements to ensure all objects are disposed ? • At what point am I doing something wrong and should I consider revision ? • If revision is required due to too many nested using statements , what are my options ? You might end up with a formidable hierarchy , but your code should be quite efficient , right ? Or should you only put , for instance , the SqlDataAdapter object in a using statement and it will somehow ensure that all the other objects get disposed as well ? Thanx . <code> using ( SqlCommand scmFetch = new SqlCommand ( ) ) { // code } string sQuery = @ '' SELECT [ ID ] , [ Description ] FROM [ Zones ] ORDER BY [ Description ] `` ; DataTable dtZones = new DataTable ( `` Zones '' ) ; using ( SqlConnection scnFetchZones = new SqlConnection ( ) ) { scnFetchZones.ConnectionString = __sConnectionString ; scnFetchZones.Open ( ) ; using ( SqlCommand scmdFetchZones = new SqlCommand ( ) ) { scmdFetchZones.Connection = scnFetchZones ; scmdFetchZones.CommandText = sQuery ; using ( SqlDataAdapter sdaFetch = new SqlDataAdapter ( ) ) { sdaFetch.SelectCommand = scmdFetchZones ; sdaFetch.Fill ( dtZones ) ; } } if ( scnFetchZones.State == ConnectionState.Open ) scnFetchZones.Close ( ) ; }
Trying to understand the 'using ' statement better
C_sharp : Here is a typical function that returns either true/false ; Now on an error , I would like to return my own custom error object with definition : I would have expected to be able to throw this custom object for example ... This is not possible , and I do n't want to derive Failure from System.IO.Exception because I have personally had issues serializing exceptions in C # ( This was with .net v2 ) . What is the best practice / or ideal solution to this problem . Should I just work with private static object ? Or is there a cleaner way to return a custom object or bypass the typical return type on an error ( not using System.IO.Exception ) ? I am not entirely wild about using an object either , because then I need to validate the result by using casting and more boolean . <code> private static bool hasValue ( ) { return true ; } public class Failure { public string FailureDateTime { get ; set ; } public string FailureReason { get ; set ; } } private static bool hasValue ( ) { try { ... do something } catch { throw new Failure ( ) ; } return true ; }
C # Possible to have a generic return type ?
C_sharp : I have some code that relied on methods not being inlined : Of course this does only work if the DoSomething method is not inlined . This is the reason why the base class derives from MarshallByRefObject , which prevent inlining of public methods.It worked until now , but I got a stacktrace from a .Net 4 server showing that the stackwalk reached the caller of DoSomething.Is the .Net 4 inlining more clever and detect that MyClass is internal and has no chance of being substituted with a proxy ? <code> internal class MyClass : BaseClass { // should not be inlined public void DoSomething ( int id ) { base.Execute ( id ) ; } } public abstract class BaseClass : MarshallByRefObject { [ MethodImpl ( MethodImplOptions.NoInlining ) ] protected void Execute ( params object [ ] args ) { // does a stack walk to find signature of calling method } }
Does .Net 4 inline MarshalByRefObject methods ?
C_sharp : I know I can use AutoFixture to create an auto-mocked instance usingBut , if I want to customise the way a Person is created I have several options . One is to use BuildAnd another is to use CustomizeSo , my question is , what are the various merits and pitfalls of each approach listed above , and are there any other / better approaches ? <code> var person = fixture.Create < Person > ( ) ; var person = fixture.Build < Person > ( ) .With ( x = > x.FirstName , `` Owain '' ) .Create ( ) ; fixture.Customize < Person > ( c = > c.With ( x = > x.FirstName , `` Owain '' ) ) ; var person = fixture.Create < Person > ( ) ;
AutoFixture Customize vs Build
C_sharp : I would expect the last line to throw an OperationCanceledException after a second , but instead it hangs forever . Why ? <code> NamedPipeServerStream server=new NamedPipeServerStream ( `` aaqq '' ) ; var ct=new CancellationTokenSource ( ) ; ct.CancelAfter ( 1000 ) ; server.WaitForConnectionAsync ( ct.Token ) .Wait ( ) ;
CancellationToken not working with WaitForConnectionAsync
C_sharp : As you see in the above code I need to convert someEnumType to byte array type before calling base class constructor . Is there a way to do it ? Something like : <code> public class bar { public bar ( list < int > id , String x , int size , byte [ ] bytes ) { ... } } public class Foo : Bar { public Foo ( list < int > id , String x , someEnumType y ) : base ( id , x , sizeof ( someEnumType ) , y ) { //some functionality } } public class Foo : Bar { public Foo ( list < int > id , String x , someEnumType y ) { //someEnumType to byte array base ( ... ) } }
Calling a base class constructor in derived class after some code block in derived constructor
C_sharp : I 'm trying to write a quicksort for my own edification . I 'm using the pseudocode on wikipedia as a guide . My code works . It seems like it should run in O ( n log n ) time . I tried actually timing my code to check the complexity ( i.e. , when I double the input size , does the run time increase by approximately n log n ) , but I 'm still not sure.My code seems pretty simple . I do the sort in-place . Other implementations I 've seen use a partition function , which I do n't have . This makes me think that I 've implemented some other sorting algorithm . Is this a quicksort algorithm ? Second version based on Dukeling 's response . <code> public static void QuickSortInPlace ( int [ ] arr ) { QuickSortInPlace ( arr , 0 , arr.Length - 1 ) ; } private static void QuickSortInPlace ( int [ ] arr , int left , int right ) { if ( left < right ) { //move the middle int to the beginning and use it as the pivot Swap ( arr , left , ( left + right ) / 2 ) ; int pivotIndex = left ; int pivot = arr [ pivotIndex ] ; int min = left + 1 ; int max = right ; for ( int i = min ; i < = max ; i++ ) { if ( arr [ i ] > pivot ) { Swap ( arr , i , max ) ; max -- ; //no longer need to inspect ints that have been swapped to the end i -- ; //reset the loop counter to inspect the new int at the swapped position } } //move pivot to its sorted position Swap ( arr , max , pivotIndex ) ; //recurse on the sub-arrays to the left and right of the pivot QuickSortInPlace ( arr , left , max - 1 ) ; QuickSortInPlace ( arr , max + 1 , right ) ; } } public static void QuickSortInPlace3 ( int [ ] arr , int min , int max ) { if ( min < max ) { int pivotIndex = min ; int pivot = arr [ pivotIndex ] ; int left = min ; int right = max ; while ( left < = right ) { while ( arr [ left ] < pivot ) left++ ; while ( arr [ right ] > pivot ) right -- ; if ( left < = right ) { Swap ( arr , left , right ) ; left++ ; right -- ; } } QuickSortInPlace3 ( arr , min , right ) ; QuickSortInPlace3 ( arr , left , max ) ; } }
Is This a QuickSort ?
C_sharp : I 'm pretty familiar with the async/await pattern , but I 'm bumping into some behavior that strikes me as odd . I 'm sure there 's a perfectly valid reason why it 's happening , and I 'd love to understand the behavior.The background here is that I 'm developing a Windows Store app , and since I 'm a cautious , conscientious developer , I 'm unit testing everything . I discovered pretty quickly that the ExpectedExceptionAttribute does n't exist for WSAs . Weird , right ? Well , no problem ! I can more-or-less replicate the behavior with an extension method ! So I wrote this : And lo , it works beautifully.So I continued happily writing my unit tests , until I hit an async method that I wanted to confirm throws an exception under certain circumstances . `` No problem , '' I thought to myself , `` I can just pass in an async lambda ! `` So I wrote this test method : This , surprisingly , throws a runtime error . It actually crashes the test-runner ! I made an overload of my AssertThrowsExpectedException method : and I tweaked my test : I 'm fine with my solution , I 'm just wondering exactly why everything goes pear-shaped when I try to invoke the async Action . I 'm guessing because , as far as the runtime is concerned , it 's not an Action , I 'm just cramming the lambda into it . I know the lambda will happily be assigned to either Action or Func < Task > . <code> public static class TestHelpers { // There 's no ExpectedExceptionAttribute for Windows Store apps ! Why must Microsoft make my life so hard ? ! public static void AssertThrowsExpectedException < T > ( this Action a ) where T : Exception { try { a ( ) ; } catch ( T ) { return ; } Assert.Fail ( `` The expected exception was not thrown '' ) ; } } [ TestMethod ] public async Task Network_Interface_Being_Unavailable_Throws_Exception ( ) { var webManager = new FakeWebManager { IsNetworkAvailable = false } ; var am = new AuthenticationManager ( webManager ) ; Action authenticate = async ( ) = > await am.Authenticate ( `` foo '' , `` bar '' ) ; authenticate.AssertThrowsExpectedException < LoginFailedException > ( ) ; } public static async Task AssertThrowsExpectedException < TException > ( this Func < Task > a ) where TException : Exception { try { await a ( ) ; } catch ( TException ) { return ; } Assert.Fail ( `` The expected exception was not thrown '' ) ; } [ TestMethod ] public async Task Network_Interface_Being_Unavailable_Throws_Exception ( ) { var webManager = new FakeWebManager { IsNetworkAvailable = false } ; var am = new AuthenticationManager ( webManager ) ; Func < Task > authenticate = async ( ) = > await am.Authenticate ( `` foo '' , `` bar '' ) ; await authenticate.AssertThrowsExpectedException < LoginFailedException > ( ) ; }
Unexpected behavior when passing async Actions around
C_sharp : Currently I 'm working with some libraries applying deferred execution via iterators . In some situations I have the need to `` forward '' the recieved iterator simply . I.e . I have to get the IEnumerable < T > instance from the called method and return it immediately.Now my question : Is there a relevant difference between simply returning the recieved IEnumerable < T > or re-yielding it via a loop ? <code> IEnumerable < int > GetByReturn ( ) { return GetIterator ( ) ; // GetIterator ( ) returns IEnumerable < int > } // or : IEnumerable < int > GetByReYielding ( ) { for ( var item in GetIterator ( ) ) // GetIterator ( ) returns IEnumerable < int > { yield return item ; } }
What is the exact difference between returning an IEnumerable instance and the yield return statement in C #
C_sharp : I have an array of lists : I want to extract all elements that are common in at least 2 lists . So for this example , I should get all elements [ `` a '' , `` b '' , `` c '' , `` d '' ] . I know how to find elements common to all but could n't think of any way to solve this problem . <code> var stringLists = new List < string > [ ] { new List < string > ( ) { `` a '' , `` b '' , `` c '' } , new List < string > ( ) { `` d '' , `` b '' , `` c '' } , new List < string > ( ) { `` a '' , `` d '' , `` c '' } } ;
how to find members that exist in at least two lists in a list of lists
C_sharp : Is there another way of declaring my ProductController for the logger that is being injected ? Thank you , Stephen <code> public class ProductController : Controller { private readonly LoggingInterface.ILogger < ProductController > _logger ; private readonly IProductRepository _productRepository ; public ProductController ( LoggingInterface.ILogger < ProductController > logger , IProductRepository productRepository ) { _logger = logger ; _productRepository = productRepository ; } {
How to infer the type of an object and use that type in a generic parameter during construction
C_sharp : I 've been working on getting long running messages working with NServiceBus on an Azure transport . Based off this document , I thought I could get away with firing off the long process in a separate thread , marking the event handler task as complete and then listening for custom OperationStarted or OperationComplete events . I noticed the OperationComplete event is not received by my handlers most cases . In fact , the only time it is received is when I publish it immediately after the OperationStarted event is published . Any actual processing in between somehow prevents the completion event from being received . Here is my code : Abstract class used for long running messagesTest ImplementationOperation EventsHandlersI 'm certain that the context.Publish ( ) calls are being hit because the _logger.Info ( ) calls are printing messages to my test console . I 've also verified they are hit with breakpoints . In my testing , anything that runs longer than 500 milliseconds prevents the handling of the OperationComplete event.If anyone can offer suggestions as to why the OperationComplete event is not hitting the handler when any significant amount of time has passed in the ProcessMessage implementation , I 'd be extremely grateful to hear them . Thanks ! -- Update -- In case anyone else runs into this and is curious about what I ended up doing : After an exchange with the developers of NServiceBus , I decided on using a watchdog saga that implemented the IHandleTimeouts interface to periodically check for job completion . I was using saga data , updated when the job was finished , to determine whether to fire off the OperationComplete event in the timeout handler . This presented an other issue : when using In-Memory Persistence , the saga data was not persisted across threads even when it was locked by each thread . To get around this , I created an interface specifically for long running , in-memory data persistence . This interface was injected into the saga as a singleton , and thus used to read/write saga data across threads for long running operations.I know that In-Memory Persistence is not recommended , but for my needs configuring another type of persistence ( like Azure tables ) was overkill ; I simply want the OperationComplete event to fire under normal circumstances . If a reboot happens during a running job , I do n't need to persist the saga data . The job will be cut short anyway and the saga timeout will handle firing the OperationComplete event with an error if the job runs longer than a set maximum time . <code> public abstract class LongRunningOperationHandler < TMessage > : IHandleMessages < TMessage > where TMessage : class { protected ILog _logger = > LogManager.GetLogger < LongRunningOperationHandler < TMessage > > ( ) ; public Task Handle ( TMessage message , IMessageHandlerContext context ) { var opStarted = new OperationStarted { OperationID = Guid.NewGuid ( ) , OperationType = typeof ( TMessage ) .FullName } ; var errors = new List < string > ( ) ; // Fire off the long running task in a separate thread Task.Run ( ( ) = > { try { _logger.Info ( $ '' Operation Started : { JsonConvert.SerializeObject ( opStarted ) } '' ) ; context.Publish ( opStarted ) ; ProcessMessage ( message , context ) ; } catch ( Exception ex ) { errors.Add ( ex.Message ) ; } finally { var opComplete = new OperationComplete { OperationType = typeof ( TMessage ) .FullName , OperationID = opStarted.OperationID , Errors = errors } ; context.Publish ( opComplete ) ; _logger.Info ( $ '' Operation Complete : { JsonConvert.SerializeObject ( opComplete ) } '' ) ; } } ) ; return Task.CompletedTask ; } protected abstract void ProcessMessage ( TMessage message , IMessageHandlerContext context ) ; } public class TestLongRunningOpHandler : LongRunningOperationHandler < TestCommand > { protected override void ProcessMessage ( TestCommand message , IMessageHandlerContext context ) { // If I remove this , or lessen it to something like 200 milliseconds , the // OperationComplete event gets handled Thread.Sleep ( 1000 ) ; } } public sealed class OperationComplete : IEvent { public Guid OperationID { get ; set ; } public string OperationType { get ; set ; } public bool Success = > ! Errors ? .Any ( ) ? ? true ; public List < string > Errors { get ; set ; } = new List < string > ( ) ; public DateTimeOffset CompletedOn { get ; set ; } = DateTimeOffset.UtcNow ; } public sealed class OperationStarted : IEvent { public Guid OperationID { get ; set ; } public string OperationType { get ; set ; } public DateTimeOffset StartedOn { get ; set ; } = DateTimeOffset.UtcNow ; } public class OperationHandler : IHandleMessages < OperationStarted > , IHandleMessages < OperationComplete > { static ILog logger = LogManager.GetLogger < OperationHandler > ( ) ; public Task Handle ( OperationStarted message , IMessageHandlerContext context ) { return PrintJsonMessage ( message ) ; } public Task Handle ( OperationComplete message , IMessageHandlerContext context ) { // This is not hit if ProcessMessage takes too long return PrintJsonMessage ( message ) ; } private Task PrintJsonMessage < T > ( T message ) where T : class { var msgObj = new { Message = typeof ( T ) .Name , Data = message } ; logger.Info ( JsonConvert.SerializeObject ( msgObj , Formatting.Indented ) ) ; return Task.CompletedTask ; } }
NServiceBus events lost when published in separate thread
C_sharp : I am uploading a file ( image ) using < asp : FileUpload / > and in the codebehind I use UploadedFile.SaveAs ( `` C : //Path ... '' ) to save the image on the server.This is my complete code : The problem is that it seems to reduce the quality . Here are some examples : The left image is the one I want to upload and the right one is the one uploaded on the server.This worked thanks to Ashigore : I 've stored the bytes in a variable and saved the raw bytes to the server as an image file . <code> protected void btnAddImage_OnClick ( object sender , ImageClickEventArgs e ) { //_fuImage is the ID of the < asp : FileUpload / > _fuImage.SaveAs ( Server.MapPath ( fullPath ) ) ; } byte [ ] imageBytes = _fuImage.FileBytes ; File.WriteAllBytes ( Server.MapPath ( fullPath ) , imageBytes ) ;
Quality reduces after UploadedFile.SaveAs ( `` '' )
C_sharp : Quick question about using nested disposables in a single 'using ' statement : Should I write out each disposable 's using statement , or can I nest them into one ? Example : vs.Just curious if when the block is done executing , the unnamed FileStream from `` myFile.txt '' gets cleaned up because it 's in the using statement with the GZipStream or if it stays open and needs to be cleaned up sometime after that.Edit : Just to be clear , I 'm not asking about nesting using statements . I 'm asking whether or not an IDisposable that is created inside another IDisposable 's 'using ' statement will be disposed of at the end of the block . Any explanation on why or why not would be appreciated . <code> using ( FileStream inFile = new FileStream ( `` myFile.txt '' , FileMode.Open ) ) using ( GZipStream gzip = new GZipStream ( inFile , CompressionMode.Decompress ) ) using ( FileStream outFile = new FileStream ( `` myNewFile.txt '' , FileMode.CreateNew ) ) { gzip.CopyTo ( outstream ) ; } using ( GZipStream gzip = new GZipStream ( new FileStream ( `` myFile.txt '' , FileMode.Open ) , CompressionMode.Decompress ) ) using ( FileStream outFile = new FileStream ( `` myNewFile.txt '' , FileMode.CreateNew ) ) { gzip.CopyTo ( outstream ) ; }
Nesting 'IDisposable 's in a single 'using ' statement
C_sharp : I 'm working on Unity and trying hard to make a custom SelectableButton that stores method ( s ) in two different delegates , and executes one whenever the button is selected and the other when it is deselected . The relevant part shows like that : On another script , I try to encapsulate a method in onSelect and another in onDeselect.In the end , I end up with an error telling me that I ca n't `` convert void to OnSelectAction/OnDeselectAction '' . And if I try to write it rather this way : The Select ( ) and Deselect ( ) methods do n't execute the way they are supposed to . If someone could help in giving me the part that I 'm lacking to make this work , it would be nice and I 'd be grateful for the hand : ) <code> public delegate void OnSelectAction ( ) ; public delegate void OnDeselectAction ( ) ; public class SelectableButton : MonoBehaviour { private bool selected ; public OnSelectAction onSelect ; public OnDeselectAction onDeselect ; public bool Selected { get { return selected ; } set { selected = value ; if ( selected ) onSelect ( ) ; else onDeselect ( ) ; } } } for ( int i = 0 ; i < racesData.RaceList.Count ; i++ ) { selectableButton.onSelect = Select ( racesData.RaceList [ i ] ) ; selectableButton.onDeselect = Deselect ( racesData.RaceList [ i ] ) ; } public void Select ( Race race ) { // Does its selection stuff } public void Deselect ( Race race ) { // Does its deselection stuff } selectableButton.onSelect = ( ) = > Select ( racesData.RaceList [ i ] ) ; selectableButton.onDeselect = ( ) = > Deselect ( racesData.RaceList [ i ] ) ;
Delegates for OnSelect and OnDeselect purposes
C_sharp : gives the error : 'System.Void ' can only be used as 'typeof ' in F # butdoes not compile . Same error , `` System.Void can only be used as typeof ... '' F # void* does compilebut using it in C # throws a design-time convert error ' can not convert from 'void* ' to 'System.IntPtr'though passing the managed IntPtr will compilebut when someAllocIntPtr is the result of Marshal.AllocHGlobal , it throws a runtime exception External component has thrown an exception..As I understand it , this happens because someAllocIntPtr ( as the result of Marshal.AllocHGlobal ) is technically a managed pointer TO an unmanaged pointer , not the same as a normal IntPtr . This is noted by Peter Ritchie in a reply to his answer here : System.Runtime.InteropServices.SEHException ( 0x80004005 ) : External component has thrown an exceptionThe only way to avoid this runtime Exception is to wrap the handle in a SecureHandle ( ) subclass , but I think that 's against the ref-ref\out-out rule on MSDN : CA1021 : Avoid out parameters.IE , System.Void* realPointer = someAllocIntPtr.ToPointer ( ) is the ACTUAL pointer ( a reference to an unmanaged pointer ) , or in other words , SecureHandle safeHandle = new SecureHandle ( someAllocIntPtr ) is actually `` a reference of - another reference of - an actual pointer '' , and should not be passed with out or ref keywords , according to the MSDN article . <code> [ < DllImport ( `` kernel32 '' ) > ] extern bool CloseHandle ( System.Void* handle ) ; //System.Void also throws same error //extern bool CloseHandle ( System.Void handle ) ; extern bool CloseHandle ( typeof < System.Void > handle ) ; extern bool CloseHandle ( void* handle ) ; public void CloseBeforeGarbageCollection ( IntPtr someAllocIntPtr ) { //test unmanaged block var result = CloseHandle ( someAllocIntPtr.ToPointer ( ) ) ; return result ; } //test managed IntPtrvar result = CloseHandle ( someAllocIntPtr ) ; //throws error at runtime
Is there a C # & VB compatible System.Void* in F # ? ( To close a pointer to nonmanaged Alloc ? )
C_sharp : I 'm trying to implement the generic method which is intended for converting objects of Tuple < Descendant > type to objects of Tuple < Ancestor > type . I 've stuck with a problem which seems to be a limitation of the C # language.Questions : Do you have any idea how to make this code working ( take in account important comment in the code sample ) ? If no , then how would you recommend me to work it around ? I want to keep the code simple and clear . <code> using System ; namespace Samples { public static class TupleExtensions { public static Tuple < SuperOfT1 > ToSuper < T1 , SuperOfT1 > ( this Tuple < T1 > target ) where T1 : SuperOfT1 { return new Tuple < SuperOfT1 > ( target.Item1 ) ; } } public interface Interface { } public class Class : Interface { } static class Program { static void Main ( ) { var tupleWithClass = new Tuple < Class > ( new Class ( ) ) ; // Next instruction lead the compilation to error . : ( The compiler does n't try to infer types if at least one of generic type arguments is explicitly declared . var tupleWithInterfaceIncorrect = tupleWithClass.ToSuper < Interface > ( ) ; // Next instruction is correct . But it looks ugly . var tupleWithInterfaceCorrect = tupleWithClass.ToSuper < Class , Interface > ( ) ; // The code I try to write in my software is even worse : // I need to declare more types explicitly , because my actual tuple has more dimensions . // var myTupleInProduction = tuple.ToSuper < Class1 < T > , Class2 < T > , Interface1 < T > , Interface2 < T > > ( ) ; // This code is VB.NET-like ( too verbose ) . The problem is compounded by the fact that such code is used in many places . // Can I rewrite my TupleExtensions to provide more laconic code like that : // var myTupleInProduction = tuple.ToSuper < Interface1 < T > , Interface2 < T > > ( ) ; Console.ReadKey ( ) ; } } }
How to work-around the limitations of the type inference in generic methods
C_sharp : This will print something close to : ' a ( '.Is this a bug with null-coalescing operator ? If I put date ? ? `` blablabla '' in parenthesis , it is underlined as error . <code> DateTime ? date = null ; string tmp = `` a '' + `` ( `` + date ? ? `` blablabla '' + `` ) '' ; Console.WriteLine ( tmp ) ;
Is this a bug in Visual Studio 2010 compiler ?
C_sharp : The code : I think the person who programmed this was `` just being careful , '' but out of interest what exceptions could be thrown on a line that does a string assignment like this one here ? I can think of System.OutOfMemoryException , but what others ? Thank you <code> public Constructor ( string vConnection_String ) { try { mConnection_String = vConnection_String ; } catch ( Exception ex ) { ExceptionHandler.CatchEx ( ex ) ; } }
What Exceptions Could string = string throw besides System.OutOfMemoryException ?
C_sharp : I am trying to accurately learn the status of Tasks that are kicked off by a QueueBackgroundWorkerItem thread . I can access the Task object and add them to a List of my TaskModels , and send that list object to my View.My view only ever shows one one Task status , no matter how many times I click the QueueWorkItem link , and start a new task . I 'd like to figure out a couple of things : How , in MVC , do I keep a live List of how many tasks I generated ? I assumed by sending the model to the view I would assure some permanency . Once I can do that , I assume I would be able to store the Task objects in my List . However , even in this example below , I still do n't seem to be able to know what the Status of the Task is at any given time ( it seems I can only know what it is at the time of adding it to my list ) .I am hoping someone has done something similar and can help with this.Thanks ! -JasonEDIT : The core requirements of this setup are : I need to use a QueueBackgroundWorkerItem to run a long job even if the browser gets closedI chose to embed a Task so I could learn the ongoing status of each job run . I understand that with the QBWI , that running a task would be overkill . But I could find no other way to know what the status of the QBWI is at any time.CONTROLLER : VIEW : EDIT , solution : Following Raffaeu 's advice , and the following compromises , I was able to find it as such : We are only running one task at any given time . I do n't need a listI do n't truly need the status on-demand . I only need to know when it 's completedI wanted to be able to leverage the Task ID to instantiate the task later from the ID . That proved to involve more overhead than necessary.Instead I found the feature Task.CompletedTask ( available in .NET 4.6 and up ) . This , used in async , allowed me to get the status of the Task when it is complete . Voila . Thanks to everyone for your suggestions.The best part - this long-running task will complete whether I close the browser ... or stop IIS . Miraculous . <code> List < TaskModel > taskModelList = new List < TaskModel > ( ) ; public ActionResult QueueWorkItem ( ) { Task task ; ViewBag.Message = `` State : `` ; String printPath = @ '' C : \Work\QueueBackgroundWorkerItemPractice\QueueBackgroundWorkerItemPractice\WorkerPrintFile '' + DateTime.Now.ToLongTimeString ( ) .ToString ( ) .Replace ( `` : '' , `` _ '' ) + `` .txt '' ; System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem ( cancellationToken = > { task = Task.Run ( ( ) = > { string filePath = printPath ; string text = `` File line `` ; if ( ! System.IO.File.Exists ( filePath ) ) { using ( var stream = System.IO.File.Create ( filePath ) ) { } } TextWriter tw = new StreamWriter ( printPath ) ; for ( int i = 0 ; i < 400 ; i++ ) { text = `` Line `` + i ; tw.WriteLine ( text ) ; Thread.Sleep ( 200 ) ; } tw.Close ( ) ; } ) ; var c = task.ContinueWith ( ( antecedent ) = > { taskModelList.Add ( new TaskModel ( task ) ) ; } ) ; } ) ; return View ( taskModelList ) ; } @ model List < QueueBackgroundWorkerItemPractice.Models.TaskModel > @ { ViewBag.Title = `` Queue Background Worker '' ; } < h2 > @ ViewBag.Title. < /h2 > < h3 > @ ViewBag.Message < span id= '' modelClass '' > < /span > < /h3 > < p > Use this area to provide additional information. < /p > @ { < ul > @ foreach ( var taskModel in Model ) { < li > @ taskModel.Status < /li > } < /ul > } public ActionResult QueueWorkItem ( ) { System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem ( cancellationToken = > { task = Task.Run ( async ( ) = > { String printPath = @ '' C : ... '' ; string filePath = printPath ; string text = `` File line `` ; if ( ! System.IO.File.Exists ( filePath ) ) { using ( var stream = System.IO.File.Create ( filePath ) ) { } } TextWriter tw = new StreamWriter ( printPath ) ; for ( int i = 0 ; i < 400 ; i++ ) { text = `` Line `` + i ; tw.WriteLine ( text ) ; Thread.Sleep ( 200 ) ; } tw.Close ( ) ; await Task.CompletedTask ; } ) ; var c = task.ContinueWith ( ( antecedent ) = > { taskID = task.Id ; status = task.Status.ToString ( ) ; try { string connString = WebConfigurationManager.ConnectionStrings [ `` TaskContext '' ] .ToString ( ) ; sqlCommand.CommandText = `` INSERT INTO dbo.TaskTable ( TaskId , Status ) VALUES ( `` + taskID + `` , ' '' + status + `` ' ) '' ; conn.ConnectionString = connString ; sqlCommand.Connection = conn ; conn.Open ( ) ; sqlCommand.ExecuteNonQuery ( ) ; } catch ( Exception ex ) { String info = ex.Message + ex.ToString ( ) + ex.StackTrace ; throw new Exception ( `` SQL Issue '' + info ) ; } finally { if ( conn ! = null ) { conn.Close ( ) ; conn = null ; } sqlCommand = null ; } } ) ; } ) ; return View ( ) ; }
How to store the active status of a Task , and maintain permanency of a List of these Tasks
C_sharp : I have a simple synchronous method , looking like this : Since the method is part of a web application , it is good to use all resources as effectively as possible . Therefore , I would like to change the method into an asynchronous one . The easiest option is to do something like this : I am not an expert on either async/await or IEnumerable . However , from what I understand , using this approach `` kills '' the benefits of IEnumerable , because the Task is awaited until the whole collection is loaded , thus omitting the `` laziness '' of the IEnumerable collection.On other StackOverflow posts I have read several suggestions for using Rx.NET ( or System.Reactive ) . Quickly browsing through the documentation I have read that IObservable < T > is their asynchronous alternative to IEnumerable < T > . However , using the naive approach and trying to type the following just did not work : I got an compilation error , that IObservable < T > does implement neither GetEnumerator ( ) , nor GetAwaiter ( ) - thus it can not use both yield and async . I have not read the documentation of Rx.NET deeper , so I am probably just using the library incorrectly . But I did not want to spend time learning a new framework to modify a single method . With the new possibilities in C # 7 it is now possible to implement custom types . Thus I , theoretically , could implement an IAsyncEnumerable , which would define both GetEnumerator ( ) and GetAwaiter ( ) methods . However , from my previous experience , I remember an unsuccessful attempt to create a custom implementation of GetEnumerator ( ) ... I ended up with a simple List , hidden in a container.Thus we have 4 possible approaches to solve the task : Keep the code synchronous , but with IEnumerableChange it to asynchronous , but wrap IEnumerable in a Task < T > Learn and use Rx.NET ( System.Reactive ) Create a custom IAsyncEnumerable with C # 7 featuresWhat are the benefits and drawbacks of each of these attempts ? Which of them has the most significant impact on resource utilization ? <code> public IEnumerable < Foo > MyMethod ( Source src ) { // returns a List of Oof objects from a web service var oofs = src.LoadOofsAsync ( ) .Result ; foreach ( var oof in oofs ) { // transforms an Oof object to a Foo object yield return Transform ( oof ) ; } } public async Task < IEnumerable < Foo > > MyMethodAsync ( Source src ) { var oofs = await src.LoadOofsAsync ( ) ; return oofs.Select ( oof = > Transform ( oof ) ) ; } public async IObservable < Foo > MyMethodReactive ( Source src ) { var oofs = await src.LoadOofsAsync ( ) ; foreach ( var oof in oofs ) { yield return Transform ( oof ) ; } }
Various ways of asynchronously returning a collection ( with C # 7 features )
C_sharp : It looks like in the following case the polymorphism does not work properlyI have the following definitions : Then when I call : I have `` The result is BaseInterface '' I was expecting to have `` The result is NewInterface '' as nc implement BaseClass and NewClassWhat would be the best way to get `` NewClass '' as the result ? Thanks <code> interface BaseInterface { } interface NewInterface : BaseInterface { } class NewClass : NewInterface { } class GenericClass < T > where T : BaseInterface { public string WhoIAm ( T anObject ) { return TestPolymorphism.CheckInterface ( anObject ) ; } } class ImplementedClass : GenericClass < NewInterface > { } class TestPolymorphism { public static string CheckInterface ( BaseInterface anInterface ) { return `` BaseInterface '' ; } public static string CheckInterface ( NewInterface anInterface ) { return `` NewInterface '' ; } } NewClass nc = new NewClass ( ) ; ImplementedClass impClass = new ImplementedClass ( ) ; Console.WriteLine ( `` The result is `` + impClass.WhoIAm ( nc ) ) ;
Polymorphism not working for a call from a generic class in C #
C_sharp : I 've read through a lot of really interesting stuff recently about regex . Especially about creating your own regex boundariesOne thing that I do n't think I 've seen done ( I 'm 100 % it has been done , but I have n't noticed any examples ) is how to exclude a regex match if it 's preceded by a 'special character ' , such as & ! % $ # . For example : If I use the regex ( Note this is from C # ) It will match any capital letters that are two or more in length , and use the \b boundary to make sure the two capital letters do n't start with or end with any other letters . But here 's where I 'm not sure how this would behave : AA -MatchsAB -No MatchACs -No Match ! AD -MatchAF ! -MatchI would like to know how to select only two or more capital letters that are n't preceded by a lower case letter/number/symbol , or followed by a lower case letter/number/special characters . I 've seen people use spaces , so make sure the string starts with or ends with a space , but that does n't work if it 's at the beginning or end of a line.So , the output I would look for from the example above would be : AA -MatchsAB -No MatchACs -No Match ! AD -No MatchAF ! -No MatchAny help is appreciated . <code> ( [ A-Z ] { 2 , } \\b )
How can I match two capital letters together , that are n't preceded by special characters , using regex ?
C_sharp : I 'm using Visual Studio 2013 currently and I write this simple code : Obviously this is not a valid C # code , but the weird part is even though I see two errors , the code is compiling and working fine : I 'm thinking that migth be relevant with Roslyn because I installed Roslyn User Preview and other extensions , but the project template I 'm using is standart Console Application template.So , why this code is compiling even though there is three compiler errors ? I tried this with VS 2012 and it does n't compile.Is that a compiler bug , or will this be valid in next version of C # ? Here is the error list I 'm seeing in VS 2012 : But there is definitely no error in VS 2013.Note : I 'm not sure whether it 's relevant or not but I 'm also using the Resharper . <code> class Program { private static void Main ( string [ ] args ) { Console.WriteLine ( string error = `` Hello world ! `` ) ; } }
Why is my IDE complaining about new syntax after I 've installed Roslyn ?
C_sharp : ( I realize that my title is poor . If after reading the question you have an improvement in mind , please either edit it or tell me and I 'll change it . ) I have the relatively common scenario of a job table which has 1 row for some thing that needs to be done . For example , it could be a list of emails to be sent . The table looks something like this : I 'm looking either for a standard practice/pattern ( or code - C # /SQL Server preferred ) for periodically `` scanning '' ( I use the term `` scanning '' very loosely ) this table , finding the not-completed items , doing the action and then marking them completed once done successfully . In addition to the basic process for accomplishing the above , I 'm considering the following requirements : I 'd like some means of `` scaling linearly '' , e.g . running multiple `` worker processes '' simultaneously or threading or whatever . ( Just a specific technical thought - I 'm assuming that as a result of this requirement , I need some method of marking an item as `` in progress '' to avoid attempting the action multiple times . ) Each item in the table should only be executed once.Some other thoughts : I 'm not particularly concerned with the implementation being done in the database ( e.g . in T-SQL or PL/SQL code ) vs. some external program code ( e.g . a standalone executable or some action triggered by a web page ) which is executed against the database Whether the `` doing the action '' part is done synchronously or asynchronously is not something I 'm considering as part of this question . <code> ID Completed TimeCompleted anything else ... -- -- -- -- -- -- - -- -- -- -- -- -- - -- -- -- -- -- -- -- -- 1 No blabla2 No blabla3 Yes 01:04:22 ...
Is there a standard pattern for scanning a job table executing some actions ?
C_sharp : If I call passing 0 to value : SaveOrRemove ( `` MyKey '' , 0 ) , the condition value == null is false , then CLR dont make a value == default ( T ) . What really happens ? <code> private static void SaveOrRemove < T > ( string key , T value ) { if ( value == null ) { Console.WriteLine ( `` Remove : `` + key ) ; } // ... }
What CLR do when compare T with null , and T is a struct ?
C_sharp : I have to send 10000 messages . At the moment , it happens synchronously and takes up to 20 minutes to send them all.To shorten the message sending time , I 'd like to use async and await , but my concern is if C # runtime can handle 15000 number of tasks in the worker process . Also , in terms of memory , I 'm not sure if it 's a good idea to create a list of 15000 tasks <code> // sending messages in a sync wayforeach ( var message in messages ) { var result = Send ( message ) ; _logger.Info ( $ '' Successfully sent { message.Title } . '' ) } var tasks = new List < Task > ( ) ; foreach ( var message in messages ) { tasks.Add ( Task.Run ( ( ) = > Send ( message ) ) } var t = Task.WhenAll ( tasks ) ; t.Wait ( ) ; ...
Sending 5000 messages in async way in C #
C_sharp : I 'm upgrading a system and am going through another developers code ( ASP.NET in C # ) .I came across this : Is checking the type on the setter unnecessary ? Surely , if I set the property to something other than a ReferralSearchFilterResults object , the code would n't even compile ? Am I missing something or am I right to think this can be achieved just by using : <code> private ReferralSearchFilterResults ReferralsMatched { get { if ( Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] == null || Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] .GetType ( ) ! = typeof ( ReferralSearchFilterResults ) ) return null ; else return ( ReferralSearchFilterResults ) Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] ; } set { if ( value == null ) { Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] = value ; } else if ( value.GetType ( ) == typeof ( ReferralSearchFilterResults ) ) { Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] = value ; } } } set { Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] = value ; }
Is this redundant code ?
C_sharp : I have a class which looks like this : The SessionReportSummaries view has a ClientId column , and I ’ m trying to join both a Client object and a ClientReportSummary object using this column.Unfortunately , NHibernate only wants to join the first one defined in the class , and always performs a SELECT for the second one . So in this scenario NHibernate queries the database first with : ( with lots of other joins ) , and then N of these : one for each of the N clients in question . This results in terrible performance.If I swap the positions of the Client and ClientReportSummary objects then NHibernate instead joins ClientReportSummary onto the SessionReportSummaries object , and performs a select for each Client object.Does anyone know how I can get NHibernate to perform a join for both of these ? <code> [ Class ( Table = `` SessionReportSummaries '' , Mutable = false ) ] public class SessionReportSummaries { [ ManyToOne ( Column = `` ClientId '' , Fetch = FetchMode.Join ) ] public Client Client { get ; private set ; } [ ManyToOne ( Column = `` ClientId '' , Fetch = FetchMode.Join ) ] public ClientReportSummary ClientReportSummary { get ; private set ; } } SELECT { stuff } FROM SessionReportSummaries ... left outer join Clients on this.ClientId=Clients.Id ... SELECT { stuff } FROM ClientReportSummary WHERE ClientReportSummary.ClientId = ' { id goes here } '
Multiple many-to-one joins on same column erroneously results in SELECT being performed
C_sharp : I have 4 tabs in Xamarin.Android project ( natively ) .3 tabs are loaded natively , but one tab I am loading is a Forms page ( content page ) .Here is the codes for tabs-The forms page is loaded successfully , but when I touch anywhere in that page , it crashes.Here is the exception-Updating the Xaml-When I debugged more the view of the fragment always null , I am suspecting that this is causing the issue , but not sure..Please help .. <code> public override Android.Support.V4.App.Fragment GetItem ( int position ) { switch ( position ) { case 0 : return new tab1Fragment ( ) ; case 1 : return new tab2Fragment ( ) ; case 2 : return new tab3Fragment ( ) ; case 3 : var fragment = new FormsPage1 ( ) .CreateSupportFragment ( Android.App.Application.Context ) ; return fragment ; default : return null ; } } System.NullReferenceException : Object reference not set to an instance of an object.at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ ( System.IntPtr jnienv , System.IntPtr native__this , System.IntPtr native_e ) at ( wrapper dynamic-method ) System.Object.55 ( intptr , intptr , intptr ) Unhandled Exception from source=AndroidEnvironment System.NullReferenceException : Object reference not set to an instance of an object . at Xamarin.Forms.Platform.Android.PlatformRenderer.DispatchTouchEvent ( Android.Views.MotionEvent e ) at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ ( System.IntPtr jnienv , System.IntPtr native__this , System.IntPtr native_e ) < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ContentPage xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' xmlns : local= '' clr-namespace : ClientApp '' x : Class= '' ClientApp.FormsPage1 '' > < StackLayout > < ! -- Place new controls here -- > < Label Text= '' Welcome to Xamarin.Forms ! '' HorizontalOptions= '' Center '' VerticalOptions= '' CenterAndExpand '' / > < /StackLayout >
Navigating native to forms in Xamarin gives null reference exception
C_sharp : Assume I have a declared a datatable and to this datatable I have assigned a result that gets returned from calling a stored procedure , so now , my datatable contains something like the following when accessing a row from it : if firstname is changed to first_name and age is removed , the code will obviously break because now the schema is broken , so is there a way to always keep the schema in sync with the code automatically without manually doing it ? Is there some sort of meta description file that describes the columns in the database table and updates them accordingly ? Is this a case where LINQ can be helpful because of its strongly typed nature ? <code> string name = dr [ `` firstname '' ] ; int age = ( int ) dr [ `` age '' ] ;
Is there a way to not break code if columns in a database change ?
C_sharp : The output is `` Test '' , why is n't it null ? If s1 is passed by reference to Func ( ) , then why does myString.Append ( `` test '' ) change it , but myString = null does not ? Thanks in advance . <code> class Test { static void Func ( StringBuilder myString ) { myString.Append ( `` test '' ) ; myString = null ; } static void Main ( ) { StringBuilder s1 = new StringBuilder ( ) ; Func ( s1 ) ; Console.WriteLine ( s1 ) ; } }
Passing reference type in C #
C_sharp : I have created the following classes . one base class IObject and 2 derived classes A and B.I have also created the following Service : What i want to do is get an instance of A or B but i do n't know which one i will get so i expect to get an IObject and cast it later to either A or B as shown in the example i put.What happens when i send a json string containing s2 string is that i get IObject instance and not B instance.What is wrong with the code ? Example of the client i 'm using : Edited : I have uploaded an example code to gitHub at the following link : https : //github.com/AlgoEitan/27588144The client there is a c # client ( I 've tried it with both c # and javascript - web browser client ) <code> [ KnownType ( typeof ( B ) ) ] [ KnownType ( typeof ( A ) ) ] [ DataContract ( Name = `` IObject '' ) ] public class IObject { } [ DataContract ( Name= '' A '' ) ] public class A : IObject { [ DataMember ] public string s1 { get ; set ; } // Tag Name as it will be presented to the user } [ DataContract ( Name= '' B '' ) ] public class B : IObject { [ DataMember ] public string s2 { get ; set ; } } [ ServiceKnownType ( typeof ( B ) ) ] [ ServiceKnownType ( typeof ( A ) ) ] public void GetR ( IObject obj ) { B other = ( B ) obj ; } var url = serviceURL ; var data = { s2 : `` Data '' } ; var json = JSON.stringify ( data ) ; $ .ajax ( { type : `` POST '' , url : url , data : data , contentType : `` application/json '' , dataType : 'json ' } ) ;
Polymorphism WCF deserialization does n't work
C_sharp : I ca n't seem to find an integral type that this will work on : <code> string foo = `` 9999999999999999999999999999999999999999999999999999999 '' ; long value ; if ( long.TryParse ( foo , out value ) ) { // do something }
Max integral type in C #
C_sharp : After reading this question Why do `` int '' and `` sbyte '' GetHashCode functions generate different values ? I wanted to dig further and found following behavior : Difference between ( 3 ) and ( 4 ) breaks the requirement that Equals should be symmetric.Difference between ( 2 ) and ( 4 ) is not coherent with MSDN specification that says : If the two objects do not represent the same object reference and neither is null , it calls objA.Equals ( objB ) and returns the result . This means that if objA overrides the Object.Equals ( Object ) method , this override is called.Difference between ( 3 ) and ( 5 ) means that operator == returns true , however objects are not equal in terms of Equals.Difference between ( 4 ) , ( 5 ) , ( 6 ) and ( 7 ) means that two objects are equal in terms of operator == and Equals , however they have different hash codes.I 'm very interested if anyone can explain why such in my opinion inconsistent behaviour is observed in rather fundamental .NET types . <code> sbyte i = 1 ; int j = 1 ; object.Equals ( i , j ) //false ( 1 ) object.Equals ( j , i ) //false ( 2 ) i.Equals ( j ) //false ( 3 ) j.Equals ( i ) //true ( 4 ) i == j //true ( 5 ) j == i //true ( 6 ) i.GetHashCode ( ) == j.GetHashCode ( ) //false ( 7 )
Inconsistency in Equals and GetHashCode methods
C_sharp : I have the following XAML : Resharper determines that FilteredPatients and SelectedPatient are ok based on the DataContext of the parent control . However , FilteredPatients is an ICollectionView and thus Resharper can not figure out that it contains instances of Patient , which has the properties specified in the DataGrid column bindings.Everything works fine at runtime , so how do I tell Resharper the type of item contained by FilteredPatients ? <code> < DataGrid ItemsSource= '' { Binding Path=FilteredPatients } '' SelectedItem= '' { Binding Path=SelectedPatient } '' > < DataGrid.Columns > < DataGridTextColumn Header= '' Name '' Binding= '' { Binding Path=FormattedName } '' / > < DataGridTextColumn Header= '' Date of Birth '' Binding= '' { Binding Path=BirthDate } / > < DataGridTextColumn Header= '' Gender '' Binding= '' { Binding Path=Gender } / > < DataGridTextColumn Header= '' Id '' Binding= '' { Binding Path=Id } '' / > < /DataGrid.Columns > < /DataGrid >
How do I tell Resharper the type contained by an ICollectionView ?
C_sharp : I have code similar to the following : This , of course , creates a `` Possible unintended reference comparison worked as intended '' situation . The solution to this is well documented here , and I already knew that the fix was to cast the session variable to a string as soon as I saw the code.However , the code is years old and has never been changed since it was originally written . Up until this week in our test environment , the if statement evaluated as true and executed the //do stuff section . This erroneous code IS STILL WORKING as intended in our production environment.How can this be ? There 's no reason this code as written should have ever worked as intended ; and yet it did , and still does in production . And what would have changed to make this code that should not have worked but did , suddenly stop working ( or rather , behave like it always should have ) ? <code> this.Session [ key ] = `` foo '' ; if ( ( this.Session [ key ] ? ? string.Empty ) == `` foo '' ) { //do stuff }
Possible unintended reference comparison worked as intended
C_sharp : I have several objects inheriting from ClassA , which has an abstract method MethodA.Each of these inheriting objects can allow up to a specific number of threads simutaneously into their MethodA.The catch : Threads can only be in an object 's MethodA , while no other objects ' MethodA is being processed at the same time.How can I solve this ? I am thinking about using a semaphore , but do n't know exactly how to do it , because I just ca n't wrap my head around the problem enough to get a solution.EDIT : Example code ( may contain syntax errors : ) <code> public class ClassA { public virtual void MethodA { } } public class OneOfMySubclassesOfClassA // there can be multiple instances of each subclass ! { public override void MethodA { // WHILE any number of threads are in here , THIS MethodA shall be the ONLY MethodA in the entire program to contain threads EDIT2 : // I mean : ... ONLY MethodA of a subclass ( not of a instance of a subclass ) in the entire program ... } } ... and more subclasses ...
All threads only in one method at a time ?
C_sharp : I am trying to define an extension method that can return an object of a type defined by the call.Desired Use : Cat acat = guy.GiveMeYourPet < Cat > ( ) ; Attempted implementationI have no trouble defining generic methods like this : or extension methods like this : But when I try to do what I really want : The compiler expects GiveMeYourPet ( ) to receive 2 type arguments ( even though one is implicitly provided by calling the extension method on the object guy.What can I do to make this work ? Note that I 've also tried reversing the order in which the parameters are defined , but nothing changes : The following call also does not work , because you can not have a method call in the type specifiation : <code> public static T GiveMeYourPet < T > ( Person a ) { ... } Cat acat = GiveMeYourPet < Cat > ( guy ) ; public static Cat GiveMeYourPetCat < P > ( this P self ) where P : Person , ... { ... } Cat acat = guy.GiveMeYourPetCat ( ) ; public static T GiveMeYourPet < T , P > ( this P self ) where P : Person , ... { ... } Cat acat = guy.GiveMeYourPet < Cat > ( ) ; public static T GiveMeYourPet < P , T > ( this P self ) Cat acat = guy.GiveMeYourPet < guy.GetType ( ) , Cat > ( ) ;
How can I define a generic extension method
C_sharp : We have a system which we use to charge the customers for different type of charges . There are multiple charge types and each charge type includes different charge items . The below is what I have come up with using the Factory Method , the problem with this one is that I need to be able to pass different parameters to each Calculate function depending on the charge type , how can I achieve this ? And the usage is : I need to be able to pass different type of parameters to the chargeItem.Calculate ( ) from within the foreach loop depending on the Calculate method I am calling , how can I achieve this ? I was planning to create different charge type parameter classes for each charge type , then determine the charge type and using some if else statements call the Calculate function passing the relevant parameter type but I do n't think it is a good idea . Is there a better way of doing this , or is there are another completely different way of achieving what I am trying to do here ? Thanks <code> //product abstract class public abstract class ChargeItem { public abstract List < ChargeResults > Calculate ( ) ; } //Concrete product classes public class ChargeType1 : ChargeItem { public override List < ChargeResults > Calculate ( ) { return new List < ChargeResults > { new ChargeResults { CustomerId = 1 , ChargeTotal = 10 } } ; } } public class ChargeType2 : ChargeItem { public override List < ChargeResults > Calculate ( ) { return new List < ChargeResults > { new ChargeResults { CustomerId = 2 , ChargeTotal = 20 } } ; } } public class ChargeType3 : ChargeItem { public override List < ChargeResults > Calculate ( ) { return new List < ChargeResults > { new ChargeResults { CustomerId = 3 , ChargeTotal = 30 } } ; } } //Creator abstract class public abstract class GeneralCustomerCharge { //default constructor invokes the factory class protected GeneralCustomerCharge ( ) { this.CreateCharges ( ) ; } public List < ChargeItem > ChargeItems { get ; protected set ; } public abstract void CreateCharges ( ) ; } public class AssetCharges : GeneralCustomerCharge { public override void CreateCharges ( ) { ChargeItems = new List < ChargeItem > { new ChargeType1 ( ) , new ChargeType2 ( ) } ; } } public class SubscriptionCharges : GeneralCustomerCharge { public override void CreateCharges ( ) { ChargeItems = new List < ChargeItem > { new ChargeType3 ( ) } ; } } public class ChargeResults { public int CustomerId { get ; set ; } public decimal ChargeTotal { get ; set ; } } var newAssetCharge = new AssetCharges ( ) ; foreach ( ChargeItem chargeItem in newAssetCharge.ChargeItems ) { foreach ( var item in chargeItem.Calculate ( ) ) { Console.WriteLine ( `` Asset Charges For Customer Id : { 0 } , Charge Total : { 1 } '' , item.CustomerId , item.ChargeTotal ) ; } }
Design pattern / Architecture for different charge types for a customer
C_sharp : I 'm building the unit tests for a C # MVC5 Project using Entity Framework 6 . I 'm trying to mock my BlogRepository using Moq which will then be used as an argument for the BlogController which I am attempting to test . I actually have the unit test working fine , but to do this I created a Fake BlogRepository Class , when I would much rather work out how to do it using Moq.The problem I 'm getting is that the Controller wants the argument to be of type IBlogRepository but is only seeing it as Mock . So I get an invalid arguments error . I thought this was how it was meant to be used though.Here is my attempt at creating the mock : And here is the beginning of the controller : What am I doing wrong ? or have I got the wrong idea here . Any help would be appreciated . Thanks . <code> Mock < IBlogRepository > blogRepo = new Mock < IBlogRepository > ( ) ; blogRepo.Setup ( t = > t.GetBlogByID ( It.IsAny < int > ( ) ) ) .Returns < Blog > ( blog = > new Blog ( ) ) ; public class BlogController : Controller { IBlogRepository blogRepo ; public BlogController ( IBlogRepository repoBlog ) { blogRepo = repoBlog ; }
How to Mock a Repository to use as an argument for a Controller ?
C_sharp : Why does a non-closing # region causes a compiler error ? After all , the region itself has absolutely no impact on the compiled code , right ? I believe it is because it is a preprocessor directive , but why is that ? It is n't used like the other directives after all.Why ca n't it be just ignored ? Or is there a feature I do n't know about the # region that explains why it is compiled ? Edit : I get that this example does n't compile because there 's no corresponding # endregion . But should n't it be treated as a missing closing tag in an xml comment ? I mean , it has the same importance does n't it ? Second edit : I 'm looking to understand the design decision behind making # region a preprocessor directive . Why not just a kind of comment that the IDE would recognize as a region of code that can be collapsed ? <code> class Application { # region Whatever < - Causes an error . static void Main ( string [ ] c ) { } }
Why does # region create compiling errors ?
C_sharp : I 'm looking for the best solution , performance wise , to rebuild a string by removing words that are not complete words . An acceptable word in this instance is a whole word without numbers or does n't start with a forward slash , or a back slash . So just letters only , but can include hyphen and apostrophe 's For example : String str = '' \DR1234 this is a word , 123456 , frank 's place DA123 SW1 :50 : / '' Using the above I 'd need a new string that returns the following : Str = `` this is a word , frank 's place '' I 've done some research on Regex , but I ca n't find anything that would do what I need.Final Code SnippetThanks for all your input guys - proves what a great site this is <code> var resultSet = Regex.Matches ( item.ToLower ( ) , @ '' ( ? : ^|\s ) ( ? ! [ \\\/ ] ) ( ? ! -+ ( ? : \s| $ ) ) ( ? ! '+ ( ? : \s| $ ) ) ( ? ! ( ? : [ a-z'- ] * ? - ) { 3 , } ) ( ? ! ( ? : [ a-z'- ] * ? ' ) { 2 , } ) [ a-z'- ] + [ , . ] ? ( ? =\s| $ ) '' ) .Cast < Match > ( ) .Select ( m = > m.Value ) .ToArray ( ) ;
Tidy up a string
C_sharp : Is it possible to use reflection in CompileTimeInitialize in PostSharp 3.1 ? Following code worked in 3.0 : With the 3.1 upgrade , this.locationInfo becomes Missing Property and accessing any of its properties cause NullReferenceException.Was I doing this a wrong way or has this been changed in 3.1 upgrade ? If so , can you suggest me the right way to approach this ? PS : If I set this.locationInfo in RuntimeInitialize things work properly . <code> public class TestClass { public string TestField ; [ TestAspect ] public void TestMethod ( ) { } } public class TestAspect : OnMethodBoundaryAspect { private LocationInfo locationInfo ; public override void CompileTimeInitialize ( MethodBase method , AspectInfo aspectInfo ) { this.locationInfo = new LocationInfo ( method.ReflectedType.GetField ( `` TestField '' ) ) ; } public override void OnSuccess ( MethodExecutionArgs args ) { Console.WriteLine ( this.locationInfo ) ; } }
Can Reflection be used in CompileTimeInitialize in PostSharp 3.1 ?
C_sharp : One of the nice things about linq was having infinite data sources processed lazily on request . I tried parallelizing my queries , and found that lazy loading was not working . For example ... This program fails to produce any results , presumably because at each step , its waiting for all calls to the generator to dry up , which of course is never . If I take out the `` AsParallel '' call , it works just fine . So how do I get my nice lazy loading while using PLINQ to improve performance of my applications ? <code> class Program { static void Main ( string [ ] args ) { var source = Generator ( ) ; var next = source.AsParallel ( ) .Select ( i = > ExpensiveCall ( i ) ) ; foreach ( var i in next ) { System.Console.WriteLine ( i ) ; } } public static IEnumerable < int > Generator ( ) { int i = 0 ; while ( true ) { yield return i ; i++ ; } } public static int ExpensiveCall ( int arg ) { System.Threading.Thread.Sleep ( 5000 ) ; return arg*arg ; } }
How do I get lazy loading with PLINQ ?
C_sharp : I have an ASP.NET Core 3.1 based project written using C # . I am aware that the best time to use await and async is when accessing external resources like pulling data from the database , accessing files , or making an HTTP request . This frees up the thread so more work is done instead for the thread to sit around waiting for code to finish.However , I am trying to figure out at what point using async/await will hurt performance ? Does the process of releasing the thread when await is called and retrieving a thread when the task complete have cost ? The code found next , is called asynchronously . In reality , that code does not need to be called asynchronously since all the code is executed in memory and no external requests are made.Here is the synchronous version of the above codeWill the asynchronous version of the code have higher cost/lower performance than the synchronous version due to the unnecessary await/async usage ? When will async/await do more harm than good ? <code> public interface ILocator { Task < Model > ExampleAsync ( ) ; } public class Example : Controller { public ILocator Locator { get ; set ; } public Example ( ILocator locator ) { Locator = locator ; } public async Task < IActionResult > Example ( ) { Model model = await Locator.ExampleAsync ( ) ; return View ( model ) ; } } public class Locator : ILocator { pubilc Task ExampleAsync ( ) { Example model = new Example ( ) ; model.Status = `` New '' ; return Task.CompletedTask ; } } public interface ILocator { Model Example ( ) ; } public class Example : Controller { public ILocator Locator { get ; set ; } public Example ( ILocator locator ) { Locator = locator ; } public IActionResult Example ( ) { Model model = Locator.Example ( ) ; return View ( model ) ; } } public class Locator : ILocator { pubilc Example ( ) { Example model = new Example ( ) ; model.Status = `` New '' ; } }
When is it not good to use await async ?
C_sharp : The title asks it all . We use actions , expressions with actions and callbacks quite extensively in today 's code . Can the JIT optimize these calls away by inlining them ? This would be a huge performance boost , considering callback patterns , in one form or the other is used in absurd quantities today.It is not possible for the JIT to optimize an action that might never change . For example , I do n't see any reason why an Action or a Func , marked with `` readonly '' attribute should n't be optimized.eg : IS a2 ever optimized out ? I do n't see a reason why it should n't be . <code> readonly Action a ; readonly Action a1 ; readonly Action a2 ; a = ( ) = > { } ; a1 = ( ) = > { a ( ) } ; a2 = ( ) = > { a1 ( ) } ;
Are deterministically unchangable Actions , and Funcs Inlined by the JIT ?