text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : We need to write some logs in our code . The logs are being written via a network request which logs some info ( the logger is an Http-API module ) , But we do n't want to break the whole flow if there 's an exception in the API.I do n't to use Task.Run for this kind of operation , because it 's bad.But then ...
Non awaitable as `` fire & forget '' - is it safe to use ?
C_sharp : In some obscure way a derived class which does n't add new functionality ( yet ) behaves different from it 's base class . The derived class : MyCheckButton inherits from a ( GTK # , part of the Mono project ) CheckButton . However in the following code snippet they behave differently : The underscore in the ...
Why does this derived class behave different from it 's base class
C_sharp : My situation : This gives me an error : Can not cast expression of type 'T ' to type 'T2 ' ( or Can not convert type 'T ' to 'T2 ' ) I understand that it is because neither T or T2 are constrained with class , but if I know - due to IsAssignableFrom - that I can use T where I need T2 , how can I convince comp...
Unconstrained type parameters casting
C_sharp : I initialize a property within the Controller 's Constructor.I have an Action Method which reset the property again on a button click event.Following javascript code is in my view which is called when the button is clicked.My problem is when I click the button , value of property changes in the Controller . B...
C # property value does n't get modified within Javascript/ jquery
C_sharp : Can I have two same function name with same parameters but different meaning.For example : Thank you . <code> public void test ( string name ) public void test ( string age )
function overload
C_sharp : When implementing the INotifyPropertyChanged interface in its most basic form , most people seem to implement it like this : :My question is : Why the extra assignment of var propertyChanged = PropertyChanged ; ? Is it just a matter of preference , or is there a good reason for it ? Surely the following is ju...
INotifyProperyChanged - why the extra assignment ?
C_sharp : Caution , before You read the restThis question is not about POST method , redisplaying view with submited form or binding input values to controller method parameters . It 's purely about rendering the View using html helper ( HiddenFor or Hidden - both returns the same ) .I created a simple hidden field usi...
MVC @ Html.HiddenFor renders html form with no value
C_sharp : I have written a user control , MenuItem , which inherits from a Form Label.I have a backgroundworker thread whose IsBusy property is exposed through a property in the MainForm as IsBackgroundBusy.How do I read this property from the MenuItem usercontrol ? I am currently using Application.UseWaitCursor and I ...
How do I read a property from my main form in a user control
C_sharp : Here is the code example : Now , if there was an exception inside of loggingProvider.ReadLogs ( ) method , it will be caught and traced . But if , for example , there is no ParticipantObjects [ 0 ] , this exception wo n't be caught and traced here . It seems that it has something to do with lambda expressions...
Why was exception not caught within the closure ?
C_sharp : I have a to rewrite a part of an existing C # /.NET program using Java . I 'm not that fluent in Java and am missing something handling regular expressions and just wanted to know if I 'm missing something or if Java just does n't provide such feature.I have data likeThe Regex pattern I 'm using looks like : ...
Regex Captures in Java like in C #
C_sharp : I have a RavenDB 3.5 collection `` Municipalities '' with documents structured like this : Note that the districts property can also be null.Now I 'm working on a typehead feature where you can search for both municipality names and district names . So I want to ( wildcard all ) query over both fields and als...
How to do a RavenDB query over multiple ( complex structure ) fields and return the matched values ?
C_sharp : Suppose I have a struct with just one field : This works great , until I want to do stuff like this : So , I implemented IEquatable < in T > and IComparable < in T > , but that still did n't enable any operators ( not even == , < , > = , etc . ) .So , I started providing operator overloads.For example : This ...
Do I have to define every single operator ?
C_sharp : I 'm trying to implement a strategy pattern to allow me to allow me to apply some `` benefit '' to an `` account '' . In the code below , I ca n't add my implementation of an interface to a dictionary expecting the interface . I think it 's some kind of contravariance problem , but it feels like I should be a...
Invariant inheritance problem
C_sharp : Can someone tell me if or what the difference of the following statements is : whenever I press += the first choice pops up when I click tab so I 've always left it . but I 'm wondering if I can just write the second . I 'm guessing that they both get compiled the same , but I 'm curious if that 's true . I '...
adding an event handler
C_sharp : I have a methodwhich , very descriptively , executes some work on a remote machine by : Queueing a message on a message bus signalling that work should be doneA remote agent picks up the message and executes the workThe work finishes and the agent queues a message on a message bus to say that the work is done...
Is there a way to know if a Task is being awaited ?
C_sharp : I am making my first attempt at using threads in an application , but on the line where I try to instantiate my thread I get the error 'method name expected ' . Here is my code : <code> private static List < Field.Info > FromDatabase ( this Int32 _campId ) { List < Field.Info > lstFields = new List < Field.In...
threading question
C_sharp : I am testing the Extreme Optimization C # library , precisely the nonlinear system solvers.As an example I find that I have to pass the solver the nonlinear system in the following shape : The problem is that the system I try to solve can not be specified at design time . It is a nonlinear system composed by ...
Define a function dynamically
C_sharp : I 'm working on some customized authentication code based on Microsoft 's membership stuff . While looking into the Profile functionality , I looked into the ProfileBase class found in System.Web.dll v4.0.30319 . There are a few class level variables that are declared as a type but then and then initialized t...
Microsoft is casting null to a type , should I ?
C_sharp : I am creating an MVC application where I am sending an email to JIRA . I initially had it working when I had the ModelType in the view just IssueTable , but when I changed it too ModelType ViewModelClass.ViewModel it stopped working correctly.In the controller : In the view : This initially worked but I neede...
Null value error when trying to make viewmodel item equal variable
C_sharp : I 'd like to animate a Button 's Background if the Mouse is over the Button.The Button 's Background is bound to a custom dependency property I 've created in the Code Behind of my UserControlNow if I try to animate the Button 's background by usingI get an exception that says : can not animate an immutable p...
UserControl Animate Button 's Background
C_sharp : I 'm working on programming a basic media player , and I 'm having some trouble writing polymorphic code , which is something I 've studied , but never actually implemented before.There are four relevant classes : MediaInfo , MovieInfo , Media , and Movie . MediaInfo is an abstract base class that holds infor...
Polymorphism : Deriving from a protected member in a base class ?
C_sharp : UPDATE May this post be helpful for coders using RichTextBoxes . The Match is correct for a normal string , I did not see this AND I did not see that `` ä '' transforms to `` \e4r '' in the richTextBox.Rtf ! So the Match.Value is correct - human error.A RegEx finds the correct text but Match.Value is wrong be...
Match.Value and international characters
C_sharp : I am using ASP.NET MVC and EF to create a vehicle reservation app in which a user will be able to reserve multiple vehicles for one datetime , if they want . I created a stored procedure to prevent double booking of vehicles , but am having trouble figuring out how to add the results to a list . Example : I w...
How do I create a list from stored procedure results Entity Framework
C_sharp : I have a feature that I only want to happen on Debug , but do not want to ship the dll 's that this feature requires . Is that possible to do ? I have : Of course MyAssembly is being referenced by the project . I would like MyAssembly.dll to not be shipped on a release mode . Can that be achieved ? Will using...
C # using statement inside # if DEBUG but not ship assembly
C_sharp : I am using a fairly simple DI pattern to inject my data repository into my controller classes , and I 'm getting the CA2000 code analysis warning ( Dispose objects before losing scope ) on every one of them . I know why the warning is happening , and can usually figure out how to fix it , but in this case I c...
CA2000 and Dependency Injection
C_sharp : In C # and its cousin languages , we always useBut you can also use ( I found this out only recently and while fooling around with the compiler ) I do not have any formal training in programming and everything is self-tought . I have been using { get ; set ; } without any thought just like we use 1 + 1 = 2 Is...
Using { set ; get ; } instead of { get ; set ; }
C_sharp : I have an interface with methods annotated with the Pure attribute from System.Diagnostics.Contracts : I wish to iterate over the members of the interface and check if the member is pure or not.Currently I 'm not able to get any attributes from the member info : What am I missing ? Note that I do not have a c...
Check if Generic Interface Member is `` Pure '' ( has Pure Attribute )
C_sharp : I need to process a list of records returned from a service.However the processing algorithm for a record changes completely based on a certain field on the record.To implement this , I have defined an IProcessor interface which has just one method : And I have two concrete implementations of IProcessor for t...
How to implement usage of multiple strategies at runtime
C_sharp : I have the following code : If I try this it throws an error : Can not convert bool ? to boolHaving searched for this this I 'm not sure why the error is thrown , where as it will allow me to doWhy am I unable to use .Any ( ) in this case - why is it classed as a nullable bool yet the count is n't a nullable ...
Why is ? .Any ( ) classed as a nullable bool ?
C_sharp : Is it possible to use one AdControl in a Windows 8.1 app with multiple AdUnitIds ? I followed the approach from different sources on the net to get the AdControl somewhat working , but now I 've found out ( after adding an event handler to the AdControls ErrorOccurred event ) that the error code is NoAdAvaila...
How can I use an AdControl with multiple AdUnitIds ?
C_sharp : This is confusing to me please expalin me the behaviour of this ? A declaration of a new member hides an inherited member only within the scope of the new member.CopyIn the example above , the declaration of F in Derived hides the F that was inherited from Base , but since the new F in Derived has private acc...
c # hiding confusion
C_sharp : I have the following piece of codes.When executed , the assertion passed . However , the assertion failed when the constructor for Reg class is disabled . On a closer look , I 've found that the implicit constructor of Reg class is called before Main ( ) . If the constructor of Reg class is explicitly defined...
Implicit static constructor called before Main ( )
C_sharp : I have a List of custom a datatype , simplified example ( myMovies ) : Now I am trying to remove all duplicates from myMovies but ignoring TVIndex.I have tried looking at But can not figure out how to ignore TvIndex . Is this possible ? <code> public class Movie { public Int32 TVIndex ; public string MovieNam...
Select distinct from List < t > ignoring one element
C_sharp : If I use the Resharper code cleanup function , I 'm finding my code ... is changed to ... But then Resharper makes a suggestion `` To extension method invocation '' for the Enumerable.ToList so the code goes back to ... I 've checked in the Resharper code editing options , but I ca n't see where/how I can sto...
How to stop Resharper toggling between Enumerable.ToList and Select suggestion
C_sharp : Is there a way to get MVC4 to call different actions based on a GET variable in the URL ? For example , let 's say I have the following two actions.Is there a way I can use the following URLs to have MVC4 'choose ' which action to call ? UPDATE : I am very much aware that I can use actions / urls the way they...
Different MVC4 action based on GET variable
C_sharp : Sample program below : This sample program represents the interfaces my actual program uses , and demonstrates the problem I 'm having ( commented out in FakeRepository ) . I would like for this method call to be generically handled by the base class ( which in my real example is able to handle 95 % of the ca...
Can you explain this generics behavior and if I have a workaround ?
C_sharp : I 'm stuck at this problem I would really appreciate if someone can help me solve this problem.I want to add spaces for sub-folder like this format down below . ( it must be done with recursion ) I want to add spaces for sub-folder like this format down below . ( itmust be done with recursion ) <code> using S...
Start new line with spaces
C_sharp : What happens behind the curtains when I include a function into my compiled query , like I do with DataConvert.ToThema ( ) here to convert a table object into my custom business object : and call it like thisApparently the function is not translated in to SQL or something ( how could it ) , but it also does n...
including `` offline '' code in compiled querys
C_sharp : I 've just started using C # 4.0 ( RC ) and come up with this problem : Note , I 've never tried this actual code , but I 've just looked at the results of doing GetConstructor using debugging in VS2010This is perfect for the two first classes ( 1 and 2 ) , the first one prints an actual ConstructorInfo-objec...
Reflecting constructors with default values in C # 4.0
C_sharp : I have an application that loads a list of client/matter numbers from an input file and displays them in a UI . These numbers are simple zero-padded numerical strings , like `` 02240/00106 '' . Here is the ClientMatter class : I 'm using MVVM , and it uses dependency injection with the composition root contai...
Using abstraction and dependency injection , what if implementation-specific details need to be configurable in the UI ?
C_sharp : Sometimes back I was trying the following statement in C # Does space has impact in expressions ? In what way the above statements are different ? Ramachandran <code> i+++++i // does not compile < bt > i++ + ++i // executed
Does C # has impact when evaluating /parsing expressions ?
C_sharp : Hi , I have a problem with getting data from youtube xml : address of youtube xml : http : //gdata.youtube.com/feeds/api/videos ? q=keyword & orderby=viewCountI try this , but the program does n't go into the linq inquiry.Anyone has idea , how to solve this ? Thanks ! <code> key = @ '' http : //gdata.youtube....
How to get data from xml , by linq , c #
C_sharp : I 've a filename : How can i split the above filename to 4 string groups . I tried : but i 'm not getting the above required four strings <code> NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip NewReport20140423_17255375BSIQ2wd28830-841c-4d30-95fd-a57a7aege412.zip string [ ] strFileTo...
Splitting a filename
C_sharp : I am using Linux containers on the latest Windows build Windows 10 2004 and enabled WSL 2 and Docker Desktop 2.3.0.3 ( 45519 ) .I right click the docker-compose file , and select Set as Startup Project.I then hit F5 to debug.I can see the image running with docker ps however breakpoints are not being hit.I ca...
Unable to debug dotnet core GenericHost docker container
C_sharp : I am trying to understand how inheritance works in C # . I wrote the following code : The CIL ( Common Intermediate Language ) code for the Main ( ) looks like the following : The lines in CIL that are troubling me are : After the castclass of animal to Dog type the code executes dog.OverRideMe ( ) ; . This i...
Regarding Inheritance C #
C_sharp : I try to use trial version of third party software written C # .While I try to use its API , I face up with a strange problem.I am using visual studio 2015 and I found an interesting extended method signature in their API-SDKThe second parameter type is not exist.Never seen before in C # . I try to give a gen...
Method Parameter Without A Parameter Type In C #
C_sharp : You can only have one View per class name in the DisplayTemplates folder as the class name is used as the name of the view.cshtml file.However , you can have two classes in a solution with the same name if they appear in different namespaces : Both try to use the DisplayTemplate defined by view : However in t...
How to handle MVC DisplayTemplates for two classes with the same name ( different namespaces )
C_sharp : I have many strings with numbers.I need to reformat the string to add commas after all number sequences.Numbers may sometimes contain other characters including 12-3 or 12/4e.g . `` hello 1234 bye '' should be `` hello 1234 , bye '' '' 987 middle text 654 '' should be `` 987 , middle text 654 , '' '' 1/2 is a...
C # Add comma after every number sequence in string
C_sharp : I 'm calling the following two lines . The second line crashes . : However , if I modify the values to not have ' , ' characters and remove the NumberStyles enum it works . e.g.Am I doing something wrong ? Is this a known issue ? Is there an acceptable work-around that does n't involve hacky string manipulati...
Why does NumberStyles.AllowThousands cause an exception when passing a negative number ?
C_sharp : i have following caseI have added a quickwatch in debug to some fields in my case : And now the strange behaviour also from quickwatch and of course the resultSo the addition of 8.39 + -0.49 does n't give me 7.9 but 8.39This code was running for 600k cases on at least two i had this behaviour the others behav...
Addition in C # .net does n't work in some cases
C_sharp : I have business models named Product and Category like below in which I add the validations : For the view model I have created something like this : A friend of mine suggested keeping all the validations in the view model and mapping all the properties of the business model in the view model like this : I as...
What should be in my View Models ?
C_sharp : I 'm having trouble with the Random class in .NET , I 'm implementing a threaded collection which is working fine , except for one smaller detail . The collection is a Skip list and those of you familiar with it know that for every node inserted I need to generate a new height that is < = CurrentMaxHeight+1 ,...
Problem with Random and Threads in .NET
C_sharp : I have defined an interface in F # I would like other apps in the same appdomain to implement it so that I can call Update on any that implement the interface ( I gather the implementations in an TinyIoC container ) . The return type Async < bool > can indicate if the update succeeded or not without having to...
How to define an async f # interface that can be implemented in c # ?
C_sharp : Is it possible to call a throwing C # function from a C++ call in a C # app such that the C++ stack is unwound properly ? Is there any documentation of this ? For example , please consider this C # code : Along with this C++ code : I tried this out , and the C # exception was caught successfully , but release...
How to call a throwing C # function from C++ in a C # app such that the C++ stack is unwound properly ?
C_sharp : I got some old LED board to which you 'd send some text and hang it up somewhere ... it was manufactured in 1994/95 and it communicates over a serial port , with a 16-bit MS-DOS application in which you can type in some text.So , because you probably could n't run it anywhere except by using DOSBox or similar...
How would I reverse this simple-looking algorithm ?
C_sharp : Is it possible to compare two objects without knowing their boxed types at compile time ? For instance , if I have a object { long } and object { int } , is there a way to know if the boxed values are equal ? My method retrieves two generic objects , and there 's no way to know what their inner types are at c...
Compare boxed objects in C #
C_sharp : Problem : return all records where Jon Doe = < bus_contact > OR < bus_sponsor > .Current code returns record 1 , so what modifications are required to return records 1 and 2 using just one query ? .XMLC # Edit : This is not exactly the same problem as pointed out in the possible duplicate link . Yes , it part...
How to add OR condition in LINQ while querying XML ?
C_sharp : I have about 20 functions with almost the same pattern , i run on array of Sites , create SiteOperation with Site object and perform some operation ( in this case with one param but sometimes there are none or more ) Is it possible to wrap this code , so i will just send action to lets say _sitesManagement wh...
similar function refactoring pattern
C_sharp : Failed : I wish to know what is happening behind the scenes in ToString ( ) etc to cause this behavior.EDIT After seeing Jon 's Answer : Result : Same result with capital and small ' o ' . I 'm reading up the docs , but still unclear . <code> [ Test ] public void Sadness ( ) { var dateTime = DateTime.UtcNow ;...
What is causing this behavior , in our C # DateTime type ?
C_sharp : I am instantiating a List < T > of single dimensional Int32 arrays by reflection . When I instantiate the list using : I see this strange behavior on the list itself : If I interface with it through reflection it seems to behave normally , however if I try to cast it to its actual type : I get this exception ...
Unable to cast List < int [ * ] > to List < int [ ] > instantiated with reflection
C_sharp : I 've just seen a video-class by Jon Skeet , where he talks about unit testing asynchronous methods . It was on a paid website , but I 've found something similar to what he says , in his book ( just Ctrl+F `` 15.6.3 . Unit testing asynchronous code '' ) .The complete code can be found on his github , but I h...
Was ManuallyPumpedSynchronizationContext required in Jon Skeet 's `` TimeMachine '' async unit test framework ?
C_sharp : I have the following piece of code : But the stringBuilder appends text MyNamespace.MyClass+CD instead of A or X . Why does this happen ? <code> delegate string CD ( ) ; void MyFunction ( ) { stringBuilder.Append ( ( CD ) delegate ( ) { switch ( whatever ) { case 1 : return `` A '' ; ... default : return `` X...
Anonymous function not returning the correct string
C_sharp : I need to make a connection to an API using a complicated authentication process that I do n't understand.I know it involves multiple steps and I have tried to mimic it , but I find the documentation to be very confusing ... The idea is that I make a request to an endpoint which will return a token to me that...
Authentication with hashing
C_sharp : I 'm setting up a really small Entity-Component-System example and have some problems with the component pools.Currently my entities are just IDs ( GUIDs ) which is fine.Each system has to implement the ISystem interface and is stored in a KeyedByTypeCollection . This collection makes sure , that each system ...
create performant component pooling for system loops
C_sharp : Came across the following MS Unit Test : I have never seen the use of generics when doing Assertions . This is how i would write the Assertion : What is the difference ? When i hover over the AreNotEqual ( ) overload i am using , the method is using the overload which compares two doubles ( not sure why there...
What is the difference between these two Unit Test Assertions ?
C_sharp : Hi I am trying to achive something like this ; if I can succeed on that , then I can visit this expression and get the GetData Method and use it for creating a dynamic sql query . I could do this by giving method name as a string however I do n't want to break the strongly type world of my developer friends.I...
Lambda expression that returns a delegate
C_sharp : In my program i have some very long task , which should be interruptable from GUI ( WPF ) . Any advices about threading architecture ? This task looks like N thread with such code : <code> public void DoLongOperation ( ) { for ( int i=beginPoint ; i < endPoint ; i++ ) { doSomethingStupid ( dataArray [ i ] ) ;...
Threading in C # . Interruptable task
C_sharp : I 'm writing an asp.net MVC application and decide to try Knockout.js for dynamic UI stuff . It 's a great framework it helped me so much so far . But I faced 2 problems that I ca n't solve and find any useful information on that.I 'll start with code to show you what I have and then I shall try to explain wh...
Posting Collection with Knockout.js
C_sharp : I have two different jwt auth tokens from two different providers my api accepts , setup as so : These auth providers have access to different APIs so when a access token attempts to access a API it 's not allowed to I will throw a 403 . I accomplish this with the following policy setup I am running into the ...
Using multiple authentication schemes on policy causes signature validation failures
C_sharp : People usually ask why they get always the same numbers when they use Random . In their case , they unintenionally create a new instance of Random each time ( instead of using only one instance ) , which of course leads to the same numbers the whole time . But in my case , I do need several instances of Rando...
Create different seeds for different instances of `` Random ''
C_sharp : I 've been trying to learn more about the CLR and while doing so noticed that the following interface in C # will be compiled to IL that contains some kind of `` abstract interface '' .Given that declaring an interface as abstract in C # is not valid , what does it mean to allow an abstract interface at the I...
Why does an interface get emitted at the IL level as an `` abstract interface '' ?
C_sharp : I have a DataSet with 1-3 tables , each table have a column named m_date ( string ) I want to get max value from all of them using LINQ.I know how to get each table Maximum value : but I do n't know how to get Max value from all the tables information Edit : I now have something like this which works : but I ...
Get a Maximum Date value from X tables in DataSet
C_sharp : Is there a way to make the parameters of this extension method 'intellisensible ' from my view ? At the moment , I can get a tooltip nudge of what the parameters ( in the controller action method ) are but would love to confidently IntelliSense type the parameter names for 'safety ' . Anyway , without further...
LINQ extension method help sought II
C_sharp : to avoid confusion I summarised some code : When I debug the code I get an InvalidCastException in Main ( ) .I know that ISpecificEntity implements IIdentifier.But obviously a direct cast from an IManager < ISpecificEntity > into an IManager < IIdentifier > does not work.I thought working with covariance coul...
How to implement generic polymorphism in c # ?
C_sharp : I was toying with Await/Async and CancellationTokens . My code works , but what happens to the Task when it 's Cancelled ? Is it still taking up resources or is it garbage collected or what ? Here is my code : <code> private CancellationTokenSource _token = new CancellationTokenSource ( ) ; public Form1 ( ) {...
What Happens To a Task When It 's Cancelled ?
C_sharp : I am trying to convert Ruby 's time to C # , but I am stuck now.Here 's my try : I am new to C # , and maybe this one should be easy , and I know I want to use Extensionmethods . But since functions are not 'first class ' in C # , I am stuck for now.So , what parametertype should I use for of WhatGoesHere ? <...
Convert Ruby 's times to C #
C_sharp : I 've been testing this code at https : //dotnetfiddle.net/ : If I compile with .NET 4.7.2 I get8590917637But if I do Roslyn or .NET Core , I get8590917630Why does this happen ? <code> using System ; public class Program { const float scale = 64 * 1024 ; public static void Main ( ) { Console.WriteLine ( unche...
C # overflow behavior for unchecked uint
C_sharp : I see some code of some guy that goes like this : What is while ( ... ) { ... } while ( ... ) statement ? is the following equivalent code ? <code> while ( ! ( baseType == typeof ( Object ) ) ) { ... . baseType = baseType.BaseType ; if ( baseType ! = null ) continue ; break ; } while ( baseType ! = typeof ( O...
unknown while while statement
C_sharp : I 'd like to modify a source string which is looking like and transfer it into a string with slashes to use it as a folder string which has the following structure : Do you know more elegant ways to realize this , than my solution below ? I 'm not very satisfied with my for-loops . <code> `` one.two.three '' ...
Building a new path-like string from an existing one
C_sharp : Is it possible for me to render unbundled and unminified scripts and styles for users in `` Admin '' role ? I 've searched and found how to disable bundling and minificationin Global.asax.cs Application_Start , but I want this logic to be per-user , not per app instance , so it should not only be running on a...
render unbundled assets for admin user role
C_sharp : Background : I will be working on tools that will be dependent on a rapidly changing API and rapidly changing data model over which I will have zero control . Data model and API changes are common , the issue here is that my code must continue to work with current and all past versions ( ie 100 % backwords co...
Suggestions for change tolerance
C_sharp : Using Reflector or DotPeek , the System.Linq.Data.Binary implementation of the equality operator overload looks like this : I must be missing something obvious , or there is a mechanism taking place of which I 'm unaware ( such as implicitly calling object == within the body ? ) . I admit , I rarely if ever n...
Referencing equality operator within equality operator implementation
C_sharp : This might be a trivial question , but I did n't find any information about this : is it `` harmful '' or considered bad practice to make a type T implement IComparable < S > ( T and S being two different types ) ? Example : Should this kind of code be avoided , and if yes , why ? <code> class Foo : IComparab...
Implementing IComparable < NotSelf >
C_sharp : I 've recently come across this code in a WinForm application and I ca n't figure if there is any reason to run async code inside a Task.Run that is awaited.Would n't this code do the exact same thing without the Task.Run ? <code> public async Task SaveStuff ( ) { await Task.Run ( ( ) = > SaveStuffAsync ( ) ....
Is there any reason to run async code inside a Task.Run ?
C_sharp : In his PluralSight course Asynchronous C # 5 , Jon Skeet provides this implementation for a convenience extension method called InCOmpletionOrder : In this question , Martin Neal provides a , seemingly more elegant , implementation using yield returnBeing still somewhat new to the rigours of asynchronous prog...
Is there a reason to prefer one of these implementations over the other
C_sharp : I 'm learning C # ( background in C++ ) , and I have a question about LINQ expressions . The following two functions both do the same thing ( near as I can tell ) . The type of Wombats is System.Data.Linq.Table < Wombat > .I 'm interested to know Which is more efficient ? Does it even matter ? Is there someth...
Compare efficiency of two different LINQ statements
C_sharp : A discussion has come up at work : We 've got a class that has an IList . Fact is an abstract base class , and there are several concrete subclasses ( PopulationFact , GdpFact , etc ) .Originally we 'd query for a given fact in this fashion , i.e . by type : Now , however , the question 's been raised whether...
Performance of Linq query by type
C_sharp : I have this situation ( drastically simplified ) : Here is typical implementation : So on a HexGrid , the client can make a call to get a point on a dual grid , with exactly the right type : So far so good ; the client does not need to know anything about the type how the two points relate , all she needs to ...
Expressing type relationships and avoiding long type parameter lists in C #
C_sharp : At my work I have to maintain some C # projects . The original developer is not around anymore . Lately I noticed some strange code mostly found in situations like this : What is the 0.ToString ( ) for ? Most of the code was written under stress , so I can think of two possibilities : It 's a placeholder ( li...
Strange Exception Handling dummy instruction
C_sharp : I thought the whole reason for Interfaces , Polymorphism , and a pattern like Inversion of Control via Dependency Injection was to avoid tight coupling , separation , modularity , and so on.Why then do I have to explicitly `` wire up '' an Interface to a concrete class like in ASP.NET ? Wo n't me having the r...
Why do I have to `` wire up '' Dependency Injection in ASP.NET MVC ?
C_sharp : In Java I can specify generic with wildcard `` ? '' . It is possible to create a map like this one : Map < String , ? > .I 'm working with C # and I need a Dictionary < String , SomeInterface < ? > > ( where ? can be int , double , any type ) . Is this possible in C # ? EDIT : Example : I was trying to map th...
Question about generics in C # comparing to Java
C_sharp : I 'm writing a system that underlies programmer applications and that needs to detect their access to certain data . I can mostly do so with properties , like this : Then I go in and tweak the get and set accessors so that they handle the accesses appropriately . However this requires that the users ( applica...
An `` elegant '' way of identifying a field ?
C_sharp : I 'm building a book library app , I have a abstract book Class , two types of derived books and two Enums that will save the genre of the book.Each Book can be related to one genre or more.Now i want to save the discounts based on the book genres ( no double discounts , only the highest discount is calculate...
selecting correct list of Enums from 2 derived classes
C_sharp : I 'm working on an engine which is meant to be configurable by the user ( not end user , the library user ) to use different components.For example , let 's say the class Drawer must have an ITool , Pencil or Brush , and an IPattern , Plain or Mosaic . Also , let 's say a Brush must have an IMaterial of eithe...
Using Generics in a non-collection-like Class
C_sharp : I have the following action methods : When I hit submit received model in POST method is incomplete . It contains FirstName , LastName etc . But UserID is null . So I ca n't update object . What am I doing wrong here ? <code> public ActionResult ProfileSettings ( ) { Context con = new Context ( ) ; ProfileSet...
Model object incomplete when try to update
C_sharp : Please take a look at the code . It should n't take long to have a glimpse.Since GetCourse ( ) returns a reference of _items , calling t.GetCourses ( ) .Clear ( ) ; is clearing the underlying Course-list in the Teacher instance . I want to prevent this behaviour . That is , the GetCourse ( ) would return a li...
List < T > is cleared problem
C_sharp : I have a following design in Java ( 7 ) application : There is a method where i pass collection of objects of some type and object that I call `` predicate '' that is used to filter given collection.Predicate is an interface with one method called test - it takes an object and return a boolean value.In such s...
How to achieve similar design ( from Java ) that use interface and implementing classes , using delegates in C #
C_sharp : I 'm trying to append some numbers to a string , that string already contains Persian character and StringBuilder always appends Persian number to the string.Even when I 'm explicitly using English numbers like ones in the above code , I still end up with Persian numbers . How can I append English numbers to ...
StringBuilder appends Persian Numbers
C_sharp : Each item has an interface , IItem . As well as this , there is a interface known as IDrawableItem which inherits from Item.The code below , is trying to draw a drawable item , but can not as the collection this class stores accepts only IItem . You can add anything that inherits from IItem to this class , bu...
Casting and interface inheritance
C_sharp : What ( if any ) is the upside or downside ( performance , good coding practice , garbage collection etc . ) of invoking a non-static method of a class in the manner below : as against the more `` traditional '' way ofAny thoughts would be greatly appreciated . <code> new ClassA ( ) .MethodA ( param1 , param2 ...
Invoking nonstatic methods of a class