text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I 'm using the Microsoft.AspNetCore.Authentication.JwtBearer and System.IdentityModel.Tokens.Jwt packages for my .NET Core project.When configuring the services I 'm adding logic to the OnTokenValidated event.Since I know the context only returns me the token without the signature I would like to know how I c...
get signature from TokenValidatedContext
C_sharp : This compiles : This does not : error CS0030 : Can not convert type 'string ' to 'char* ' I can not find the spot in the c # spec which allows the first syntax but prohibit the second . Can you help and point out where this is talked about ? <code> string s = `` my string '' ; unsafe { fixed ( char* ptr = s )...
Converting string to pointer syntax
C_sharp : Given ( Simplified description ) One of our services has a lot of instances in memory . About 85 % are unique . We need a very fast key based access to these items as they are queried very often in a single stack / call . This single context is extremely performance optimized.So we started to put them them in...
Replacement .net Dictionary
C_sharp : This question is a follow-up to comments in this thread.Let 's assume we have the following code : Furthermore , let 's assume that no instruction in ( 2 ) has any effect on the nonVolatileField and vice versa.Can the reading instruction ( 3 ) be reordered in such a way that in ends up before the lock stateme...
Can a read instruction after an unrelated lock statement be moved before the lock ?
C_sharp : I am doing simple WinForms application , and I am facing some strange problem.My form : It is as easy as it can be : 3 comboboxes , and two buttons - OK and Cancel.View : What happens after caling method applyOrderButton_Click ( ) ( it happens after Ok button is clicked ) all of my comboBoxes change selected ...
ComboBoxes are linked ( and that is bad )
C_sharp : Is there a reason why I ca n't use the following code ? It shows me : The following will work : I know how to solve the problem . I just want to know the reason.Thanks . <code> ulong test ( int a , int b ) { return a == b ? 0 : 1 ; } Can not implicitly convert type 'int ' to 'ulong ' . An explicit conversion ...
return ulong in inline-if
C_sharp : For example , if roots = { 2,10 } it would select 20 twice . Is it possible to avoid duplicates here ? <code> var multiples = from i in Enumerable.Range ( min , ( max - min ) ) from r in roots where i % r == 0 select i ;
C # Trying to avoid duplicates
C_sharp : Suppose How come when ChangeViewEvent is fired , event handler is still able to access variable i ? I mean should n't it be out of scope or something ? <code> public class Program { public static void Main ( string [ ] args ) { Program p = new Program ( ) ; A a = new A ( ) ; p.Do ( a ) ; System.Threading.Thre...
c # events : how variables are accessed
C_sharp : Suppose I have a list of items ( e.g. , Posts ) and I want to find the first item according to some non-trivial ordering ( e.g. , PublishDate and then CommentsCount as a tie-breaker ) .The natural way to do this with LINQ is like this : However , the micro-optimizer in me is worried that calling OrderBy actua...
How to find the first item according to a specific ordering using LINQ in O ( n ) ?
C_sharp : I have a form that loads and generates 7 different random numbers , from 1-13 , 1 being Ace , and 13 being King . After generating 7 different random numbers , it puts each of those random numbers into the 7 picture boxes . I 'm displaying the picture boxes using the if statement.It also cycles through an arr...
C # I have 50+ else if statements for cards , is there a way to make it shorter or do it all at one go ?
C_sharp : Is it possible to call a method on the type you pass into your generic method ? Something like : <code> public class Blah < T > { public int SomeMethod ( T t ) { int blah = t.Age ; return blah ; } }
Is it possible to call a method on the type you pass into your generic method ?
C_sharp : I have this functionlater when i sayresult must be in compilation time a string type , but that not happened , why ? In fact , the compilar pass thisand not thisAnything help please ? <code> string F ( dynamic a ) { return `` Hello World ! `` ; } dynamic a = 5 ; var result = F ( a ) ; int result2 = F ( a ) ; ...
Problems with dynamic parameter
C_sharp : I 've created three .NET Standard class librariy C # projects with Visual Studio 2017 and default settings.Projects : MainProjectTimeProjectDependencies - > MainProjectClockProjectDependencies - > TimeProjectEach of them must have its own output directory like : The project DLL files are placed the output dir...
Multiple DLLs from referenced .NET Standard projects
C_sharp : All online examples I can find for C # 's using instantiate directly within the using parentheses : I would think that the following should act identically , but I still seem to have locked resources : When I step through my program and get to the line following the using 's closing brace , I 'd expect to be ...
C # using : constructor in a different method
C_sharp : If I have a DateTime , and I do : I get the Year as String . But Also if I do the differences is only that the second one doesnt get an exception if there is n't the Date ? ( which i prefeer ) <code> date.Year.ToString ( ) date.Year + `` ''
What 's the differences between .ToString ( ) and + `` ''
C_sharp : I know that I can create an immutable ( i.e . thread-safe ) object like this : However , I typically `` cheat '' and do this : Then I got wondering , `` why does this work ? '' Is it really thread-safe ? If I use it like this : Then what it 's really doing is ( I think ) : Allocating space on the thread-share...
Does using private setters only in a constructor make the object thread-safe ?
C_sharp : Okay so I have a pretty good idea of how to use co-routines in Unity3d but I want to make a reusable component for deferred execution that allows me to take code like thisTaking that and convert it to something like thisTo be used like thisI 've tried implementing that in the followingthinking that that might...
Co-routine Wrapper not executing callback in a timely manner
C_sharp : Why do a lot of people do enums this way : instead of just doing : Are there advantages ? <code> public enum EmployeeRole { None = 0 , Manager = 1 , Admin = 2 , Operator = 3 } public enum EmployeeRole { None , Manager , Admin , Operator }
What is the point of using ints as enums
C_sharp : I am creating a xsl stylehseet and came up with this ( in my opinion illogical behavior ) : This XPath : /root/element [ 1 ] [ @ attr1 ! = ' 1 ' or @ attr2 ! = 'test ' ] is WAY slower than this XPath : /root/element [ count ( preceding-sibling : :element ) + 1 = 1 ) and ( @ attr1 ! = ' 1 ' or @ attr2 ! = 'tes...
XPath explicit index filter performance
C_sharp : I would like to assign a property string to below attribute.so extraction is my string but I do n't want hard code into there . Any suggestions on better way to assign <code> [ ExtractKeyAttribute ( ** '' Extraction '' ** ) ] public class Extract { ... . }
How can I assign a property to an attribute
C_sharp : I have the following code ( from Google Doc Api resources ) to fetch changes from google drive . However , I want to retrieve the changes made by each user on a specific google doc . Is there a way to achieve this ? <code> var _driveService = GetDriveServiceInstance ( ) ; var requestxx = _driveService.Changes...
Retrieving changes made by each user on a specific google doc
C_sharp : I have this function which checks for proxy servers and currently it checks only a number of threads and waits for all to finish until the next set is starting . Is it possible to start a new thread as soon as one is finished from the maximum allowed ? <code> for ( int i = 0 ; i < listProxies.Count ( ) ; i+=n...
C # Multithreading with slots
C_sharp : What I am really asking is this ; if there are dependencies which are impossible to compile into the unity build , is there a way of still calling them from within the unity and simply using the scripts loaded into the browser from the website and communicating with them ? Relevant documentation does not addr...
Unity - communicating with clientside Javascript and ajax . How to pass data back to the webpage from unity ?
C_sharp : I was reading a bit on generic variance and I do n't have a full understanding of it yet but I 'd like to know if it makes something like the following possible ? <code> class A < T > { } class B { } class C : B { } class My1 { public My1 ( A < B > lessDerivedTemplateParameter ) { } } class My2 : My1 { public...
Can C # 4.0 variance help me call a base class constructor with an upcast ?
C_sharp : I 've been looking to create a regex for my specific situation . The furthest i 've come with my own limited knowledge of Regex and by searching on StackOverflow is this Regex : I 'm looking for a Regex which forces the string to : start with the letter ' p ' or ' P ' , so lower and uppercaseis not shorter th...
Looking for specific regex
C_sharp : I have several classes that take a dependency of type ILogger . The implementation of ILogger needs to know the type for which it is the logger , i.e . the ILogger for Foo will be new Logger ( typeof ( Foo ) ) , for Bar it will be new Logger ( typeof ( Bar ) ) , etc.I would like the proper logger to be inject...
How to use the type being resolved to resolve a dependency
C_sharp : You can always define a class like this : and then use it like this : Can we not do something like this : Just a short way of initializing when underlying object definition is simple and predictable . This is possible in JavaScript ( I have seen examples in Angular ) .Sorry if this is answered before , my qui...
Initialize a List < T > with inline definition of < T >
C_sharp : I have a web service that uses the Entity Framework for storage and exposes a public API for CRUD operations.If I have an entity such as User which has a 1 to many relationship with a Car entity , how do I easily return in my web service method of GetUser ( int userId ) a instance of user that looks like this...
How do I return an entity that is a query of multiple tables
C_sharp : Is it possible to get a full StackTrace object WITH line numbers at any given point in the codeI found this : That gives me the full stacktrace from where I am in execution . But it does not include line numbers.I also found this : That gives me the line numbers , but only for one frame of the StackTrace ( no...
Get full stack trace with line numbers
C_sharp : I recently noticed a couple of articles that mentioned creating SQLite connections all in common code . Is this something new as I have always done it this way with an interface : Is there a way this could all be accomplished in common code rather than in the implementation below that requires code in Common ...
With Xamarin Forms , how can I create my SQLite connections in shared code ?
C_sharp : I have n't been able to find anything on google . I have this piece of code : and I am having trouble actually understanding what each element does.It generates a range of numbers and elements between 0 and 11 . But what does the select ( x = > x / 2 ) do ? does it just make pairs of elements , I know what th...
Clarify what select does
C_sharp : if i have this code : is there anything that support doing something like this : so it will accept anything that supports one of two interfaces . I am basically trying to create an overload . <code> public interface IJobHelper { List < T > FilterwithinOrg < T > ( IEnumerable < T > entities ) where T : IFilter...
In C # , can you put an Or in an `` where '' interface constraint ?
C_sharp : Is this the simplest way to determine if foo is the same or derived from type Tand an exact match would be <code> bool Derives < T > ( object foo ) { return foo is T ; } bool ExactMatch < T > ( object foo ) { return foo.GetType ( ) == typeof ( T ) ; }
Simplest way to determine if class x is derived from class y ? ( c # )
C_sharp : I have some code for an XNA tower defense . I have it set so that the enemy ( bug ) goes on a random path down from a certain side of the grid until it hits the house ( destination ) or the row on the side of the house.I debugged this project and the bug gets drawn and starts moving in a diagonal ( kind of ) ...
Why wo n't my random path code work ?
C_sharp : On my VS 2015 compiler , I tested thatBut this is a documented behavior ? NULL by definition , is an undefined behavior , so comparing NULL to another NULL could be undefined . It could happen that on my machine , using my current .Net framework , the two NULLs turn out to be the same . But in the future , th...
Is String NULL always equal to another String NULL in C # ?
C_sharp : I 'm trying to create a simple reporting tool , where a user can select from a set of KPI 's , charts , aggregate functions and other parameters , click a button , after which a wcf service is called , which then returns a custom model with all data . This could then be displayed in an MVC/WPF application ( c...
Generic interfaces for semi-ad hoc report
C_sharp : I have implemented the following class : I feel like something this simple & useful should be in .NET somewhere . Also , I realize that the class I made is somewhat incorrect . The class is designed to work with objects that do n't have a default constructor , yet my 'where ' clause requires it in all cases.L...
Does C # .NET have an allocation helper class similar to mine ?
C_sharp : I usually send data back to the calling code using return . However this time I have to send two kinds of data : Is it possible for me to send the value of runTime back to the calling code ? <code> public IEnumerable < AccountDetail > ShowDetails ( string runTime )
Can I use a parameter in C # to send data back to the caller ?
C_sharp : Possible Duplicate : What is the static variable initialization order in C # ? For fun i ran this code I was not expecting 2 2 3 . I was expecting a compiler error ( circlur dependency ) or 8 5 3.What are the rules to initialization order in C # ? -edit- i tried making a not static and i got what i expected ....
What are the rules to initialization order in C # ?
C_sharp : currently I have a master rota which is storing appointments along with the TIME and DAY but not DATE . The SQL Server database looks like the below for the master rota appointments It is created via the DAYPILOT calendar controlAs you can see there is time stored but not a DATE but it is storing the Day . E....
DayPilot SQL - Copying appointments that dont have a Date
C_sharp : In my development environment , I have a user that I just received an OAuth Token for the following scopes.https : //www.googleapis.com/auth/calendar https : //www.googleapis.com/auth/calendar.eventshttps : //www.googleapis.com/auth/calendar.readonlyEverything looks fine and I store the token for the user . I...
Google Calendar API returns invalid_grant and bad request
C_sharp : After I upgraded to DotNet 4.5 , a query started giving me OutOfMemoryExceptions.The ( distilled ) query is : I 'm posting this for anyone with the same problem . I 'll answer below . <code> var tests = new int [ ] { } .AsParallel ( ) .GroupBy ( _ = > _ ) .Take ( int.MaxValue ) .ToArray ( ) ;
Why would OutOfMemoryException be thrown while using PLINQ Take ( ) ?
C_sharp : I am facing a problem with drawing Newton 's fractal for f ( x ) = x^3 - 1 using F # The problem is that my program seems to draw only the down right 1/4 of the fractal and nothing else . Since the actual drawn area is correct , I take it as the problem might be with the bitmap representation on the FormHere ...
1/4 of Newton 's fractal is drawn only
C_sharp : I recall hearing once that throwing an object of some type other than System.Exception ( or those extending it ) was technically legal CIL , though C # has no feature to support it . So I was interested to see that the following C # code : compiles to the following CIL : where we see that the nested general c...
Any real-world implications for general catch clause emitting System.Object as type filter ?
C_sharp : In C # 9 , one can define a property with the same name in a record both in its primary constructor and in its body : This code compiles without errors.When initializing an instance of such a record , the value provided to the constructor is completely ignored : printsIs this behavior correct or is it a bug ?...
Defining a property in a record twice
C_sharp : According to MSDN , it is a bad practice to catch exceptions without a specific type and using for example System.Net.ExceptionDo I have to dig into the msdn manual to see the possible exception types each time I 'm going to catch an error . Or is there any way in the IDE to let me see this quickly . Currentl...
how to know possible exceptions when using try catch ?
C_sharp : NOTE : Clarified some of my question at the bottom.I am wondering if there might be a ( sane ) pattern to deal with request/response from older mainframe systems ? In the examples below , IQ is the request and RSIQ is the response . In the first example , I am requesting a list of all account codes and in the...
Is there a Pattern for dealing with mainframe data ?
C_sharp : I 've the given condition from a cpp source.I want to translate this into C # .When I understand this right , this means as much as if activeFace is *not* in faces then ... - not ? So what would be the equivalent in C # ? Note : I ca n't use faces.HasFlag ( activeFace ) Well it should be Am I right ? For the ...
Translating bitwise comparison from C++ to C #
C_sharp : I did a test like below ↓ 1 ) Create a customer enum ( copy from the dayofweek ) 2 ) Create two test method ... 3 ) Main method4 ) The result : I really do n't know why the system type enum is slower than the customer enum type ... .Could anybody tell me why ? Thank you ... UPDATE EDIT : Add the [ ComVisible ...
Is there any difference between Customer Enum Type and System Enum Type
C_sharp : i have a method that read some files and get hashes SHA1Managed and then compare it with other hashes from a list , how can i do this method on other thread ? <code> public bool CheckFile ( string file , string filehash ) { if ( File.Exists ( file ) ) { using ( FileStream stream = File.OpenRead ( file ) ) { S...
C # execute method on other thread
C_sharp : C # compiler can correctly infer type of s ( string ) in these snippets : But it ca n't in this one [ 1 ] : To make it work one has to do something like this : orAnd the question is - why type inference does n't work in [ 1 ] if all needed information about types is known beforehand ? <code> Func < int , stri...
IEnumerable < Func < T , S > > and LINQ type inference
C_sharp : This is my if-statement at the moment : Is there anyway I can reduce this statement ? Should I build this if-statement in a for-loop ? BTW , this if-statement if already in a forloop and it uses the i of the forloop <code> if ( excel_getValue ( `` A '' + i ) == `` '' & & excel_getValue ( `` A '' + ( i + 1 ) )...
Reduce the if-statement itself
C_sharp : I 'm trying to use StreamWriter to log a search every time someone searches on my program . I can get StreamWriter to write a new file but it does not create any content . I 've tried searching google for the proper use and to me it looks like I 've done it correctly . If you can read my code and tell me wher...
C # - StreamWriter Is Creating My File But No Content
C_sharp : I am trying to sign an XML file in C # using Signature Class library by Microsoft.What I have done is like this-And it is working completely fine . But I have an issue with this code . I have to use TSA Server for the stored time in the XML Signature , but the time is set from local PC , to avoid this issue ,...
Configure TSA in Xml Signature in C #
C_sharp : The documentation for the keyword `` is '' states that : The is operator only considers reference conversions , boxing conversions , and unboxing conversions . Other conversions , such as user-defined conversions , are not considered.What does it mean in practice ? Is it wrong to use it to check if a struct i...
The `` is '' keyword and the override of Equals method
C_sharp : I have a program in which I read from a string that 's formatted to have a specific look.I need the numbers which are separated by a comma ( e.g . `` A , B , D , R0,34 , CDF '' - > '' A '' , '' B '' , '' D '' , '' R0 '' , `` 34 '' , `` CDF '' ) . There are commas between letters that much is guaranteedI have ...
How to break a single string into an array of strings ?
C_sharp : Given this short example program : When run , it will produce an exception similar to : Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : `` object ' does not contain a definition for 'Count '' Meaning compiler chose dynamic as a preferred type of chars variable . Is there any reason for it not to choos...
Why does compiler infer var to be dynamic instead of concrete type ?
C_sharp : I have a bunch of methods that look like these two : I have one method for each property in my pFBlock object . with so little changing between methods I feel like there should be a better way to do this , but I ca n't think of any.I 'm using VS 2005 . <code> public void SourceInfo_Get ( ) { MethodInfo mi = p...
is it possible to refactor this into a single method
C_sharp : According to the C # specification this is valid code , and it compiles and runs.where SomeEvent is : But ReSharper produces the warning : '' The event SomeEvent can only appear on the lefthand side of += or -= '' I ca n't find a way to suppress this in Options > Inspection Severity . Is it a bug in ReSharper...
ReSharper 9.2 produces warning for nameof with event name
C_sharp : What is the best way to handle the following situation in C # ? I have a server application written in C/C++.For exampleIt creates a unsigned char buffer with length 256.In this buffer the server stores the data the client sends to it . After storing , there are some cryptography checks with the received buff...
C # Array.Value differs from created array in c++
C_sharp : I am not sure if this is a Covariance and Contravariance issue but I can not get this working . Here is the code : For some reason , I can not pass PaginatedDto < PersonDto > as PaginatedDto < IDto > to ProcessDto method . Any idea how can I solve this issue ? <code> public interface IDto { } public class Pag...
Can not implicitly convert MyType < Foo > to MyType < IFoo >
C_sharp : I 'm fairly new to C # ( 6 months on the job experience ) , but it seems pretty similar to Java so I feel right at home.However , today I tried implementing the IComparer interface and wondered why it was giving me an error : It seems like it requires you to implement it as : I did n't notice anything in the ...
Why does IComparer require you to define IComparer.Compare ( Object x , Object y ) and not just Compare ( Object x , Object y ) ?
C_sharp : In the process of moving away from $ type annotations ( in order to make the data language-independent ) , I 'm having some issues understanding the priority of the various TypeNameHandling annotations and type contract.During the transiton , both the new types and old types will be contained in the same file...
Disable type annotation for specific types with Json.NET
C_sharp : The following code : Will output : Why r and rr are different ? Update : Found that this is reproduced if to select `` x86 '' platform target or to check `` Prefer 32-bit '' with `` Any CPU '' . In 64x mode works correctly . <code> double c1 = 182273d ; double c2 = 0.888d ; Expression c1e = Expression.Constan...
Compiled expression tree gives different result then the equivalent code
C_sharp : We had a discussion at work about code design and one of the issues was when handling responses from a call to a boolean method like this : One of my colleagues insists that we skip the extra variable ok and writeSince he says that using the `` bool ok '' -statement is memorywise bad.Which one is the one we s...
Boolean vs memory
C_sharp : Today while playing with a De-compiler , i Decompiled the .NET C # Char Class and there is a strange case which i do n't Understandi Used Telerik JustDecompile <code> public static bool IsDigit ( char c ) { if ( char.IsLatin1 ( c ) || c > = 48 ) { return c < = 57 ; } return false ; return CharUnicodeInfo.GetU...
Multi return statement STRANGE ?
C_sharp : I set up my OpenLDAP server on a Ubuntu 19.04 VM and allowed replication ( using this tutorial : https : //help.ubuntu.com/lts/serverguide/openldap-server.html # openldap-server-replication ) . Everything for replication seems ok.I do n't have set up a consumer server as my code will act as one , pulling modi...
Ca n't get deleted items from OpenLDAP Server using Content Synchronization Operation ( syncrepl )
C_sharp : I want to compare the response from the server with a string , but I get a false result when testing the two strings . Why ? I found this but did n't help : How do I compare strings in Java ? I tried two ways : The code does not run in either case because the value of the test is false.Full codeServer side - ...
Why do n't the two equal strings match ?
C_sharp : I have this extension method : Is it possible to exclude primitive types and IEnumerable interface from `` this Object current '' ? EditetMy question is not a duplicate , because in suggested question problem is in collision of parameters between overload methods . Author asked , is it possible to exclude Str...
Is it possible to exclude IEnumerable and primitive types from Object parameter ?
C_sharp : Possible Duplicate : Do methods which return Reference Types return references or cloned copy ? A co-worker of mine stated that when a method returns an object like the following , a new instance/copy of the object is created as opposed to passing back a reference : Is that correct ? My tests seem to indicate...
When an object is returned from a method , is a new instance or a reference created ?
C_sharp : This question is similar to LINQ group one type of item but handled in a more generic way.I have a List that has various derived classes . I may have something like this : I am trying to use LINQ to semi-sort the list so that the natural order is maintained EXCEPT for certain classes which have base.GroupThis...
LINQ - group specific types of classes
C_sharp : I 'm studying string.Normalize ( ) method and I thought it is used to compare string equality if they are using different unicode . Here 's what I 've done so far . Is the string.Equals ( ) is not what I 'm supposed to use here ? <code> string stra = `` á '' ; string straNorm = stra.Normalize ( ) ; string str...
How can I get true if we compare a to á ?
C_sharp : I have populated the follow list with objects of type AnonymousTypeMy problem is that I ca n't make it stronly typed to do something like this : However , it 's possible on this list : Can I cast my first list to make it behave like the second list ? I want to be able to use lambda expressions on the properti...
Cast List < object > to AnonymousTypes list
C_sharp : I had the following code to generate a hash of an object : I.e . I add all the properties ' hash codes and then take the hash of this.In review , a coworker suggested that this will collide too frequently . I 'm not sure that this is true because : Given that hash codes are chosen with equal frequency among p...
Will this hash function collide unusually frequently ?
C_sharp : Is there some way of defining a class such that if I mistakenly attempt to sort a List < > of the objects with no sort specifications it will generate a compile-time error ? So when I correctly specify , for exampleit will be accepted , but if I forget and specify then I 'll get a compile-time error . ( I do ...
Compile-time error wanted for List < > .Sort ( ) with no sort specification
C_sharp : If I have two constructors for a class , how does the service container choose which one to use when I 'm registering that service in ConfigureServices ? So lets say I have a class called MyClass with a corresponding interface IMyClass . In the ConfigureServices ( ) method I call the following line of codeHow...
Which constructor will be called when registering services in ConfigureServices
C_sharp : Say I have a list of orders . Each order have a reference to the customer and the product they bought . Like so : I want to group all orders where different customers have the same set of products are in the same group.Customer 1 - Product 1 & 2Customer 2 - Product 1 & 2 & 3Customer 3 - Product 1 & 2Customer ...
Linq groupby on two properties
C_sharp : I have a TextBox in xaml : I add text to it with this method : Once the text goes of out of the wrap is there a way to focus the end so the old text disappears to the left and the new on the right , as opposed to just adding it to the right without seeing . <code> < TextBox Name= '' Text '' HorizontalAlignmen...
How to follow the end of a text in a TextBox with no NoWrap ?
C_sharp : We know , if we change a collection in a foreach loop , the following exception is thrown : InvalidOperationException : Collection was modified ; enumeration operation may not execute.But there is a method that behaves differently : List < T > .Sort ( Comparison < T > ) .For example ( dotnetfiddle.net ) : Acc...
Inconsistent behavior : no exception is thrown in the List < T > .Sort method when called in a foreach loop
C_sharp : I 've inherited an MVC project and I 'm having some trouble as I am very new to MVC and web development in general.The project contains a Controller Action method which generates a view . This method can either be called when the user accesses the view directly via the UI , or to regenerate the view after the...
Problem populating the ViewBag using TempData & Redirect
C_sharp : Why this works : Output : This would make sense if the function call was dispatched to the String class , but it did n't since GetType ( ) is not virtual . <code> Object o = `` my string '' ; Console.WriteLine ( o.GetType ( ) ) ; System.String
How does GetType ( ) knows the type of a derived class ?
C_sharp : I have a class that requests that when called a string is sent when requesting / initializing it.How would it be possible to take the string `` hostname2 '' ) in the class constructor and allow this string to be called anywhere in the `` Checks '' class ? E.g . I call Checks ( hostname2 ) from the Form1 class...
Using strings from other classes C #
C_sharp : I have a comma delimited text file that contains 20 digits separated by commas . These numbers represent earned points and possible points for ten different assignments . We 're to use these to calculate a final score for the course . Normally , I 'd iterate through the numbers , creating two sums , divide an...
How to populate two separate arrays from one comma-delimited list ?
C_sharp : I 'm using Asp.Net MVC 5 with Entity Framework 6 . I 've got a table like this : Now I want to move the Food to a list of foods . Like this : If I try this and add a migration , I 'll lose the data related to Food Ids . And wo n't know which recipe is for which food.I tried keeping the Food and add the list l...
Moving items to list of items in an Entity Framework migration
C_sharp : Why is it possible to modify the value of a readonly field using reflection but not the value of a const ? I 've read this answer so I understand it 's allowed to break the rules for readonly but why not for const in that case ? I 'm sure there 's a good reason but I ca n't figure out what it could be. -- Edi...
Why is it possible to change the value of a readonly field but not of a const using reflection ?
C_sharp : I want to check TempData inside of if condition . But I am getting an error.My ControllerWhy I am getting model values in Tempdata means I want to pass the values which I am getting in TempDate to another action . So only I am using TempData . Now I am getting error . The Error is Operator == is not applied b...
Is it possible to check TempData inside if condtion in Asp.Net MVC ?
C_sharp : Let 's say I have this method in my base class.I want child class to freely modify the method , but make sure it calls Dispose ( ) first , then later it calls RaiseClosed ( ) . They can do anything in before , after , or in between the two.How can I enforce child classes to call Dispose ( ) and RaiseClosed ( ...
How can I enforce derived methods to follow a certain pattern ?
C_sharp : I have three enums : The problem is in the signature of F if I use : I get an error ( invalid arguments ) for every call in the definition of Parameter , but if I use the following instead : Everything is fine . It 's not a blocking problem , but I 'd like to understand why is that . <code> enum ValueType : i...
Values of enum as result of a function
C_sharp : Edit : Two options shown below.If you 're just using the functionality that an IDisposable provides , the aptly named using clause works fine . If you 're wrapping an IDisposable in an object , the containing object itself needs to be IDisposable and you need to implement the appropriate pattern ( either a se...
What 's the best way of returning constructed IDisposables safely ?
C_sharp : Greetings ! I 'm looking for a way to search a collection for the object that best satisfies my criteria . Since I have to do this quite often , I was looking into how to execute the query using LINQ , but can not find a simple way to do this that does n't 'appear ' to waste time.A functional implementation w...
How to do a 'search a take best ' function in LINQ ?
C_sharp : Consider this code snippet and try to guess what y1 and y2 evaluate toYou might say -Aha- double is a value type and so the value returned by the extension method is a copy of the main x . But when you change the above into delegates of classes the results are still different . Example : So the two functions ...
Why do these two functions not return the same value ?
C_sharp : I 'm fetching string from output file which will always be either Ok or Err.After that I 'm casting this result Ok or Err to Enum property , which is ok , everything works , but I 'm sure that there must be a better way than mine.Since I 'm fetching 3 characters in case that Ok is fetched I need to remove thi...
most elegant way to remove string element
C_sharp : I have enum : I need to have abbreviated version of 'MyEnum ' which maps every item from 'MyEnum ' to different values . My current approach is method which simply translates every item : the problem with this approach is that every time programmer changes MyEnum he should also change translate method . This ...
Enum item mapped to another value
C_sharp : Why I always need to assign a value to string variable , before actually using it to compare.For ex : Some input - objI get compile time error - something like - cant use unassigned variable 'temp ' . But string variable has default value as 'null ' , which I want to use . So why this is not allowed ? <code> ...
Why assign value to string before comparing , when default is null
C_sharp : I have the following code : Why does it only throw one exception when multiple errors are in the list ? <code> if ( errorList ! = null & & errorList.count ( ) > 0 ) { foreach ( var error in errorList ) { throw new Exception ( error.PropertyName + `` - `` error.ErrorMessage , error.EntityValidationFailed ) ; }...
Why does my for-each only throw one exception ?
C_sharp : i wonder how can you check which part of a if statement was the correct one . For example if you have this : Now in this case the one that made the if correct is a . So how can you verify this ? Basically you can put them in 4 different if 's but if you have to do a repetitive code for each one you can probab...
C # How to check which part of an if statement is correct
C_sharp : Derived class contains a `` Count '' method which perform some actions on class `` Derived '' .On the other hand i have an Extension Method which is also targets the class `` Derived '' .By calling above snippet will execute `` Count '' method inside the derived class . Why C # compiler not warns and identify...
Why Extension Method behaves different ?
C_sharp : In C # , if you want to read a string without having to escape the characters , you can use an at-quotewhich is equivalent to Is there a simple way to escape an entire string in Java ? <code> String file = @ '' C : \filename.txt '' String file = `` C : \\filename.txt ''
Is there a way to use something similar to c # 's at quoting ( @ '' `` ) in java
C_sharp : I have a method which internally performs different sub-operations in an order and at failure of any of the sub operation i want to Rollback the entire operation.My issue is the sub-operations are not all database operations . These are mainly system level changes like adding something in windows registry , c...
How to ensure that a system level operation is atomic ? any pattern ?
C_sharp : Is there a way to run a method based on a conditional statement like a null-coalescing/ternary operator ? Sometimes , I have something like this in my code : Is there a way I can have something like : OR <code> if ( Extender.GetSetting < string > ( `` User '' ) == null ) { ConfigureApp ( ) ; } else { loadUser...
Fast/Easy way to run a method based on a condition