lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 caneither g...
services .AddAuthentication ( JwtBearerDefaults.AuthenticationScheme ) .AddJwtBearer ( jwtBearerOptions = > { // ... set TokenValidationParameters ... jwtBearerOptions.Events = new JwtBearerEvents ( ) { OnTokenValidated = ( tokenValidatedContext ) = > { JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityT...
get signature from TokenValidatedContext
C#
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 ?
string s = `` my string '' ; unsafe { fixed ( char* ptr = s ) { // do some works } } string s = `` my string '' ; unsafe { fixed ( char* ptr = ( char* ) s ) { // do some works } }
Converting string to pointer syntax
C#
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 into a dicti...
Die Arraydimensionen haben den unterstützten Bereich überschritten . bei System.Collections.Generic.Dictionary ` 2.Resize ( Int32 newSize , Boolean forceNewHashCodes ) bei System.Collections.Generic.Dictionary ` 2.Insert ( TKey key , TValue value , Boolean add )
Replacement .net Dictionary
C#
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 statement ( 1 ) o...
// ( 1 ) lock ( padlock ) { // ( 2 ) } var value = nonVolatileField ; // ( 3 )
Can a read instruction after an unrelated lock statement be moved before the lock ?
C#
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 position ....
private void applyOrderButton_Click ( object sender , EventArgs e ) { List < string > testList = new List < string > ( ) { `` A '' , `` B '' , `` C '' } ; comboBox1st.DataSource = testList ; comboBox2nd.DataSource = testList ; comboBox3rd.DataSource = testList ; comboBox1st.SelectedIndex = 2 ; comboBox2nd.SelectedIndex...
ComboBoxes are linked ( and that is bad )
C#
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 .
ulong test ( int a , int b ) { return a == b ? 0 : 1 ; } Can not implicitly convert type 'int ' to 'ulong ' . An explicit conversion exists ( are you missing a cast ? ) ulong test ( int a , int b ) { return false ? 0 : 1 ; }
return ulong in inline-if
C#
For example , if roots = { 2,10 } it would select 20 twice . Is it possible to avoid duplicates here ?
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#
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 ?
public class Program { public static void Main ( string [ ] args ) { Program p = new Program ( ) ; A a = new A ( ) ; p.Do ( a ) ; System.Threading.Thread.Sleep ( 1000 ) ; a.Fire ( ) ; } public void Do ( A a ) { int i = 5 ; a.ChangeViewEvent += ( ) = > { Console.WriteLine ( i ) ; } ; } } public class A { public delegate...
c # events : how variables are accessed
C#
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 actually costs ...
posts.OrderBy ( post = > post.PublishDate ) .ThenBy ( post = > post.CommentsCount ) .First ( )
How to find the first item according to a specific ordering using LINQ in O ( n ) ?
C#
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 array of `` S...
if ( cardNum == 1 & & cardType == `` Spades '' ) { pictureBox1.Image = ace_of_spades ; } else if ( cardNum == 1 & & cardType == `` Hearts '' ) { pictureBox1.Image = ace_of_hearts ; } else if ( ... ) { //change picture box } //repeat it like 50 times
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#
Is it possible to call a method on the type you pass into your generic method ? Something like :
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#
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 ?
string F ( dynamic a ) { return `` Hello World ! `` ; } dynamic a = 5 ; var result = F ( a ) ; int result2 = F ( a ) ; int result3 = F ( 5 ) ;
Problems with dynamic parameter
C#
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 directories b...
< OutputPath > C : \Projects\DataControl\Build\MainProject < /OutputPath > < OutputPath > C : \Projects\DataControl\Build\TimeProject < /OutputPath > < OutputPath > C : \Projects\DataControl\Build\ClockProject < /OutputPath > < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netstandard2.0 ...
Multiple DLLs from referenced .NET Standard projects
C#
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 able to al...
using ( var cnx = new SqlConnection ( ) ) { } SqlConnection GetConnection ( ) { return new SqlConnection ( ) ; } void foo ( ) { using ( var cnx = GetConnection ( ) ) { } }
C # using : constructor in a different method
C#
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 )
date.Year.ToString ( ) date.Year + `` ''
What 's the differences between .ToString ( ) and + `` ''
C#
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-shared heap for...
class CantChangeThis { private readonly int value ; public CantChangeThis ( int value ) { this.value = value ; } public int Value { get { return this.value ; } } } class CantChangeThis { public CantChangeThis ( int value ) { this.Value = value ; } public int Value { get ; private set ; } } var instance = new CantChange...
Does using private setters only in a constructor make the object thread-safe ?
C#
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 not work ...
StartCoroutine ( WaitForDamageCooldown ( DamageCooldown ) ) ; IEnumerator WaitForDamageCooldown ( float duration ) { yield return new WaitForSeconds ( duration ) ; HasTempInvincibility = false ; } CoroutineUtil.DeferredExecutor ( float waitTime , Action onComplete ) ; StartCoroutine ( CoroutineUtil.DeferredExecutor ( W...
Co-routine Wrapper not executing callback in a timely manner
C#
Why do a lot of people do enums this way : instead of just doing : Are there advantages ?
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#
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 ! = 'test ' ) ] I ...
< ? xml version= '' 1.0 '' encoding= '' iso-8859-1 '' ? > < root > < element attr2= '' test '' attr1= '' 1 '' > < child > 17 < /child > < child > 17 < /child > < child > 16 < /child > ... < child > 3 < /child > < child > 2 < /child > < child > 1 < /child > < /element > < element attr2= '' test2 '' attr1= '' 2 '' > < ch...
XPath explicit index filter performance
C#
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
[ ExtractKeyAttribute ( ** '' Extraction '' ** ) ] public class Extract { ... . }
How can I assign a property to an attribute
C#
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 ?
var _driveService = GetDriveServiceInstance ( ) ; var requestxx = _driveService.Changes.GetStartPageToken ( ) ; var response = requestxx.Execute ( ) ; var savedStartPageToken = response.StartPageTokenValue ; // Begin with our last saved start token for this user or the// current token from GetStartPageToken ( ) string ...
Retrieving changes made by each user on a specific google doc
C#
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 ?
for ( int i = 0 ; i < listProxies.Count ( ) ; i+=nThreadsNum ) { for ( nCurrentThread = 0 ; nCurrentThread < nThreadsNum ; nCurrentThread++ ) { if ( nCurrentThread < nThreadsNum ) { string strProxyIP = listProxies [ i + nCurrentThread ] .sIPAddress ; int nPort = listProxies [ i + nCurrentThread ] .nPort ; tasks.Add ( T...
C # Multithreading with slots
C#
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 address this d...
gameInstance = UnityLoader.instantiate ( `` gameContainer '' , `` /Build/DomumProto16_Web.json '' , { onProgress : UnityProgress } ) ; gameInstance.SendMessage ( 'Manager ' , 'Filter ' , JSON.stringify ( filterActive ) ) ; function showStudentWork ( studentIndex ) { //make sure to remove all the var x = document.getEle...
Unity - communicating with clientside Javascript and ajax . How to pass data back to the webpage from unity ?
C#
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 ?
class A < T > { } class B { } class C : B { } class My1 { public My1 ( A < B > lessDerivedTemplateParameter ) { } } class My2 : My1 { public My2 ( A < C > moreDerivedTemplateParameter ) : base ( moreDerivedTemplateParameter ) // < -- compile error here , can not convert { } }
Can C # 4.0 variance help me call a base class constructor with an upcast ?
C#
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 than 19 char...
^ [ pP ] [ a-zA-Z0-9- ] *
Looking for specific regex
C#
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 injected automat...
interface ILogger { ... } class Logger : ILogger { private readonly Type _type ; public Logger ( Type type ) { _type = type ; } ... } class Foo { private readonly ILogger _logger ; public Foo ( ILogger logger ) // here I want a Logger with its type set to Foo { _logger = logger ; } }
How to use the type being resolved to resolve a dependency
C#
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 quick search ...
public class item { int id ; string name ; } List < item > items = new List < item > ( ) ; var items = new List < { int id , string name } > ( ) ;
Initialize a List < T > with inline definition of < T >
C#
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 : Does th...
public class User { string Id ; IEnumberable < Car > Cars ; }
How do I return an entity that is a query of multiple tables
C#
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 ( not a full S...
var stackTrace = new StackTrace ( ) ; var stackTrace = new StackTrace ( new StackFrame ( 1 , true ) ) ;
Get full stack trace with line numbers
C#
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 , iOS and ...
namespace Memorise { public interface ISQLiteDB1 { ( SQLiteConnection , bool ) GetConnection ( ) ; } } [ assembly : Dependency ( typeof ( ISQLiteDB_iOS ) ) ] namespace Memorise.iOS { public class ISQLiteDB_iOS : ISQLiteDB { public ( SQLite.SQLiteConnection , bool ) GetConnection ( string _dbName ) { bool newDb = false ...
With Xamarin Forms , how can I create my SQLite connections in shared code ?
C#
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 the whole th...
Random r = new Random ( ) ; int [ ] output = Enumerable.Range ( 0 , 11 ) .Select ( x = > x / 2 ) .OrderBy ( x = > r.Next ( ) ) .ToArray ( ) ;
Clarify what select does
C#
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 .
public interface IJobHelper { List < T > FilterwithinOrg < T > ( IEnumerable < T > entities ) where T : IFilterable ; } public interface IJobHelper { List < T > FilterwithinOrg < T > ( IEnumerable < T > entities ) where T : IFilterable or ISemiFilterable }
In C # , can you put an Or in an `` where '' interface constraint ?
C#
Is this the simplest way to determine if foo is the same or derived from type Tand an exact match would be
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#
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 ) path . It ...
public class Bug : Sprite { public float startHealth ; protected float currentHealth ; protected bool alive = true ; protected float speed = 0.5f ; protected int bountyGiven ; public int startplace ; public bool at_house ; public Queue < Vector2 > path = new Queue < Vector2 > ( ) ; Random random = new Random ( ) ; int ...
Why wo n't my random path code work ?
C#
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 , they could b...
static void Main ( string [ ] args ) { string str1 = null ; string str2 = null ; if ( str1==str2 ) //they are the same on my machine { } }
Is String NULL always equal to another String NULL in C # ?
C#
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 ( could be bo...
public interface IReport < T > where T : IConvertible { ICollection < IColumn < T > > Columns { get ; set ; } } public interface IColumn < T > where T : IConvertible { ICollection < IValue < T > > Values { get ; set ; } } public interface IValue < T > where T : IConvertible { T Value { get ; set ; } } public class IntV...
Generic interfaces for semi-ad hoc report
C#
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.Let me know...
public class ClassAllocator < T > where T : new ( ) { public delegate T Allocator ( ) ; T obj ; Allocator allocator = ( ) = > new T ( ) ; public ClassAllocator ( T obj ) { this.obj = obj ; } public ClassAllocator ( T obj , Allocator allocator ) { this.obj = obj ; this.allocator = allocator ; } public T Instance { get {...
Does C # .NET have an allocation helper class similar to mine ?
C#
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 ?
public IEnumerable < AccountDetail > ShowDetails ( string runTime )
Can I use a parameter in C # to send data back to the caller ?
C#
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 . Why is b ...
using System ; public class Test { public static void Main ( ) { A.t ( ) ; } } class A { static int a = B.b + c ; public static int c = 3 ; static public void t ( ) { Console.WriteLine ( `` { 0 } { 1 } { 2 } '' , a , B.b , c ) ; } } class B { public static int b = A.c+2 ; }
What are the rules to initialization order in C # ?
C#
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.G Day 0 is...
public void CreateAssignment ( DateTime start , DateTime end , int location , int week , string person , string note , DayOfWeek day ) { using ( DbConnection con = CreateConnection ( ) ) { con.Open ( ) ; //string id = `` '' ; var cmd = CreateCommand ( `` insert into [ master_rota ] ( [ AssignmentStart ] , [ AssignmentE...
DayPilot SQL - Copying appointments that dont have a Date
C#
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 then requ...
public class GoogleCalendarAdapter : ICalendarAdapter { # region attributes private readonly ISiteAuthTokenQueryRepository _tokenRepo ; private readonly GoogleCalendarSettings _settings ; private const string APPNAME = `` REDACTED '' ; private const string ACL_OWNER = `` owner '' ; private const string ACL_WRITER = `` ...
Google Calendar API returns invalid_grant and bad request
C#
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 .
var tests = new int [ ] { } .AsParallel ( ) .GroupBy ( _ = > _ ) .Take ( int.MaxValue ) .ToArray ( ) ;
Why would OutOfMemoryException be thrown while using PLINQ Take ( ) ?
C#
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 's a link ...
open Systemopen System.Drawingopen System.Windows.Formsopen System.Numericslet pi = 3.14159265359let MaxCount = 50let multCol = 15let Tol = 0.5let r1 = Complex ( 1.0 , 0.0 ) let r2 = Complex ( -0.5 , sin ( 0.66*pi ) ) let r3 = Complex ( -0.5 , -sin ( 0.66 * pi ) ) let createImage ( ) = let image = new Bitmap ( 800 , 80...
1/4 of Newton 's fractal is drawn only
C#
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 catch claus...
try { throw new Exception ( ) ; } catch ( Exception x ) { try { throw ; } catch { Console.Write ( `` yes '' ) ; } } .try { IL_0000 : newobj instance void [ mscorlib ] System.Exception : :.ctor ( ) IL_0005 : throw } // end .try catch [ mscorlib ] System.Exception { IL_0006 : pop .try { IL_0007 : rethrow } // end .try ca...
Any real-world implications for general catch clause emitting System.Object as type filter ?
C#
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 ? If it ’ s...
record Cat ( int PawCount ) { public int PawCount { get ; init ; } } Console.WriteLine ( new Cat ( 4 ) ) ; Console.WriteLine ( new Cat ( 4 ) { PawCount = 1 } ) ; Cat { PawCount = 0 } Cat { PawCount = 1 }
Defining a property in a record twice
C#
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 . Currently I 'm usi...
try { using ( WebClient goog = new WebClient ( ) ) { goog.DownloadString ( `` http : //google.com '' ) ; } } catch ( Exception E ) { saveLog ( `` methodname '' , E.Message ) ; }
how to know possible exceptions when using try catch ?
C#
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 second re...
The inquiry message has this general format : IQ~ < msg id > ~A < unit # > ~B < device type > ~D < acct # > ~F < password > ~G < file > ~H < hierarchicrecordpath > ~J < field > **One field from many records** : Beginning with first share ( ordinal zero ) on Account 101 return all the Share ID fields in firstmessage the...
Is there a Pattern for dealing with mainframe data ?
C#
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 completene...
if ( ! ( faces & activeFace ) || [ ... ] ) { ... } if ( ( faces & activeFace ) == 0 || [ ... ] ) { ... } [ Flags ] enum Face { North = 1 , East = 2 , South = 4 , West = 8 , Top = 16 , Bottom = 32 } ;
Translating bitwise comparison from C++ to C #
C#
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 ( true ) ]...
[ Serializable ] public enum Tester { // 概要 : // Indicates Sunday . Sunday = 0 , // // 概要 : // Indicates Monday . Monday = 1 , // // 概要 : // Indicates Tuesday . Tuesday = 2 , // // 概要 : // Indicates Wednesday . Wednesday = 3 , // // 概要 : // Indicates Thursday . Thursday = 4 , // // 概要 : // Indicates Friday . Friday = 5...
Is there any difference between Customer Enum Type and System Enum Type
C#
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 ?
public bool CheckFile ( string file , string filehash ) { if ( File.Exists ( file ) ) { using ( FileStream stream = File.OpenRead ( file ) ) { SHA1Managed sha = new SHA1Managed ( ) ; byte [ ] checksum = sha.ComputeHash ( stream ) ; string sendCheckSum = BitConverter.ToString ( checksum ) .Replace ( `` - '' , string.Emp...
C # execute method on other thread
C#
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 ?
Func < int , string , string > f1 = ( n , s ) = > s.Substring ( n ) ; Func < int , Func < string , string > > f2 = n = > s = > s.Substring ( n ) ; var numbers = Enumerable.Range ( 1 , 10 ) ; IEnumerable < Func < string , string > > fs = numbers.Select ( n = > s = > s.Substring ( n ) ) ; var fs = numbers.Select ( n = > ...
IEnumerable < Func < T , S > > and LINQ type inference
C#
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
if ( excel_getValue ( `` A '' + i ) == `` '' & & excel_getValue ( `` A '' + ( i + 1 ) ) == `` '' & & excel_getValue ( `` A '' + ( i + 2 ) ) == `` '' & & excel_getValue ( `` A '' + ( i + 3 ) ) == `` '' & & excel_getValue ( `` A '' + ( i + 4 ) ) == `` '' & & excel_getValue ( `` A '' + ( i + 5 ) ) == `` '' & & excel_getVa...
Reduce the if-statement itself
C#
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 where I am wro...
StreamWriter write = new StreamWriter ( `` searchLogFile.dat '' ) ; write.WriteLine ( gameTitle + `` === `` + string.Format ( `` { 0 : C } '' , saleValue ) ) ;
C # - StreamWriter Is Creating My File But No Content
C#
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 , I have ch...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Net ; using System.Security.Cryptography ; using System.Security.Cryptography.X509Certificates ; using System.Security.Cryptography.Xml ; using System.Text ; using System.Threading.Tasks ; using System.Windows ; using System.Xml ; using ...
Configure TSA in Xml Signature in C #
C#
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 is a certai...
public struct Point2D { public int X ; public int Y ; ... public override bool Equals ( Object value ) { if ( value ! = null & & value is Point2D ) // or if ( value ! = null & & GetType ( ) == value.GetType ( ) ) { Point2D right = ( Point2D ) value ; return ( X == right.X & & Y == right.Y ) ; } else return false ; } .....
The `` is '' keyword and the override of Equals method
C#
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 tried to d...
for ( int i=0 ; i < =newInput.Length ; i++ ) { while ( Char.IsLetter ( newInput [ i ] ) ) { variables [ k , j ] = ( char ) newInput [ i ] ; i++ ; k++ ; } k=0 ; j++ ; }
How to break a single string into an array of strings ?
C#
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 choose IEnumera...
static void Main ( string [ ] args ) { Console.WriteLine ( Test ( `` hello world '' ) ) ; } private static int Test ( dynamic value ) { var chars = Chars ( value.ToString ( ) ) ; return chars.Count ( ) ; } private static IEnumerable < char > Chars ( string str ) { return str.Distinct ( ) ; }
Why does compiler infer var to be dynamic instead of concrete type ?
C#
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 .
public void SourceInfo_Get ( ) { MethodInfo mi = pFBlock.SourceInfo.GetType ( ) .GetMethod ( `` SendGet '' ) ; if ( mi ! = null ) { ParameterInfo [ ] piArr = mi.GetParameters ( ) ; if ( piArr.Length == 0 ) { mi.Invoke ( pFBlock.SourceInfo , new object [ 0 ] ) ; } } } public void SourceAvailable_Get ( ) { MethodInfo mi ...
is it possible to refactor this into a single method
C#
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 ?
var myObj = new MyClass ( ) ; var x = nameof ( myObj.SomeEvent ) ; Console.Write ( x ) ; // Prints 'SomeEvent ' public event EventHandler SomeEvent ;
ReSharper 9.2 produces warning for nameof with event name
C#
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 buffer.I 'm wr...
public static byte [ ] GetCBuffer ( this byte [ ] data , int len ) { byte [ ] tmp = new byte [ len ] ; for ( int i = 0 ; i < len ; i++ ) if ( i < data.Length ) tmp [ i ] = data [ i ] ; else tmp [ i ] = 204 ; return tmp ; }
C # Array.Value differs from created array in c++
C#
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 ?
public interface IDto { } public class PaginatedDto < TDto > where TDto : IDto { public int PageIndex { get ; set ; } public int PageSize { get ; set ; } public int TotalCount { get ; set ; } public int TotalPageCount { get ; set ; } public bool HasNextPage { get ; set ; } public bool HasPreviousPage { get ; set ; } pu...
Can not implicitly convert MyType < Foo > to MyType < IFoo >
C#
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 interface ...
public class AlphabeticalReportSort : IComparer { int Compare ( Object x , Object y ) { return 0 ; } } public class AlphabeticalReportSort : IComparer { int IComparer.Compare ( Object x , Object y ) { return 0 ; } }
Why does IComparer require you to define IComparer.Compare ( Object x , Object y ) and not just Compare ( Object x , Object y ) ?
C#
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 files . Theref...
using System ; using System.Collections.Generic ; using Newtonsoft.Json ; using System.Linq ; using Newtonsoft.Json.Serialization ; namespace jsontest { // I ca n't touch this class , even to add annotations // ( in practice there are too many classes to update ) interface IDoNotTouchThis { } class DoNotTouchThisClass ...
Disable type annotation for specific types with Json.NET
C#
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 .
double c1 = 182273d ; double c2 = 0.888d ; Expression c1e = Expression.Constant ( c1 , typeof ( double ) ) ; Expression c2e = Expression.Constant ( c2 , typeof ( double ) ) ; Expression < Func < double , double > > sinee = a = > Math.Sin ( a ) ; Expression sine = ( ( MethodCallExpression ) sinee.Body ) .Update ( null ,...
Compiled expression tree gives different result then the equivalent code
C#
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 should use ...
bool ok = IsEverythingOK ( ) ; if ( ok ) { //do somehthing } if ( IsEverythingOK ( ) ) { //do somehthing }
Boolean vs memory
C#
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
public static bool IsDigit ( char c ) { if ( char.IsLatin1 ( c ) || c > = 48 ) { return c < = 57 ; } return false ; return CharUnicodeInfo.GetUnicodeCategory ( c ) == 8 ; //Is this Line Reachable if Yes How does it work ! }
Multi return statement STRANGE ?
C#
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 modified eleme...
syncRequestValue = BerConverter.Encode ( `` { iob } '' , new object [ ] { refreshOnly , cookieSrc , true } ) ; testdsrc = new DirectoryControl ( `` 1.3.6.1.4.1.4203.1.9.1.1 '' , syncRequestValue , true , true ) ; request.Controls.Add ( testdsrc ) ; connection.SendRequest ( request ) ; response = ( SearchResponse ) conn...
Ca n't get deleted items from OpenLDAP Server using Content Synchronization Operation ( syncrepl )
C#
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 - C # ( Wind...
BufferedReader in = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) , `` UTF8 '' ) ) ; String code ; if ( Objects.equals ( ( code = in.readLine ( ) ) , `` S '' ) ) { //Input string : `` S '' //code } BufferedReader in = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) , `` U...
Why do n't the two equal strings match ?
C#
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 String type f...
public static T Foo < T > ( this Object current ) where T : class , new ( ) { ... }
Is it possible to exclude IEnumerable and primitive types from Object parameter ?
C#
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 otherwise...
public CustomerEntity Customer { get ; set ; } public CustomerEntity GetCustomer ( ) { Customer = new CustomerEntity ( ) ; return Customer ; } public class CustMan { public CustomerEntity GetCustomer ( ) { Customer = new CustomerEntity ( ) ; return Customer } public void FillCustomer ( CustomerEntity customer ) { custo...
When an object is returned from a method , is a new instance or a reference created ?
C#
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.GroupThisType == tr...
List < BaseClass > list = new List < BaseClass > ( ) { new Class1 ( 1 ) , new Class2 ( 1 ) , new Class1 ( 2 ) , new Class3 ( 1 ) , new Class2 ( 2 ) , new Class4 ( 1 ) , new Class3 ( 2 ) } ; List < BaseClass > list = new List < BaseClass > ( ) { new Class1 ( 1 ) , new Class1 ( 2 ) , new Class2 ( 1 ) , new Class3 ( 1 ) ,...
LINQ - group specific types of classes
C#
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 ?
string stra = `` á '' ; string straNorm = stra.Normalize ( ) ; string strFormC = stra.Normalize ( NormalizationForm.FormC ) ; string strFormD = stra.Normalize ( NormalizationForm.FormD ) ; string strFormKC = stra.Normalize ( NormalizationForm.FormKC ) ; string strFormKD = stra.Normalize ( NormalizationForm.FormKD ) ; C...
How can I get true if we compare a to á ?
C#
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 properties like I ...
List < object > someList = new List < object > ( ) ; someList.Add ( new { foo = 1 } ) ; someList.Where ( x= > x.foo == 1 ) ; var someList = new [ ] { new { foo = 1 } } ;
Cast List < object > to AnonymousTypes list
C#
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 positive an...
public int GetHashCode ( MyType obj ) { return ( obj.Prop1.GetHashCode ( ) + obj.Prop2.GetHashCode ( ) + obj.Prop3.GetHashCode ( ) ) .GetHashCode ( ) ; }
Will this hash function collide unusually frequently ?
C#
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 realize th...
listOfMyObjects.Sort ( MyObject.CompareFieldNames ) ; listOfMyObjects.Sort ( ) ;
Compile-time error wanted for List < > .Sort ( ) with no sort specification
C#
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 does it c...
services.AddScoped < IMyClass , MyClass > ( ) ; MyClass ( ILogger logger ) MyClass ( ILogger logger , IConfguration configuration )
Which constructor will be called when registering services in ConfigureServices
C#
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 4 - Produc...
class Orders { public int CustomerId { get ; set ; } public int ProductId { get ; set ; } }
Linq groupby on two properties
C#
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 .
< TextBox Name= '' Text '' HorizontalAlignment= '' Left '' Height= '' 75 '' VerticalContentAlignment= '' Center '' TextWrapping= '' NoWrap '' Text= '' TextBox '' Width= '' 336 '' BorderBrush= '' Black '' FontSize= '' 40 '' / > private string words = `` Initial text contents of the TextBox . `` ; public async void textR...
How to follow the end of a text in a TextBox with no NoWrap ?
C#
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 ) : According to ...
List < int > list = new List < int > { 2 , 1 } ; foreach ( int i in list ) { //list.Sort ( Comparer < int > .Default ) ; // InvalidOperationException //list.Sort ( ) ; // InvalidOperationException list.Sort ( ( a , b ) = > a.CompareTo ( b ) ) ; // No exception Console.WriteLine ( i ) ; } public void Sort ( int index , ...
Inconsistent behavior : no exception is thrown in the List < T > .Sort method when called in a foreach loop
C#
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 user has ...
@ { string actionResult = ViewBag.SavedMessage ; } @ if ( ! string.IsNullOrEmpty ( actionResult ) ) { < tr > < td > @ actionResult < /td > < /tr > } public partial class ApproveController : Controller { const string IDX_ACTIONRESULT = @ '' ActionResult '' ; public ActionResult MyAction ( FormCollection collection ) { t...
Problem populating the ViewBag using TempData & Redirect
C#
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 .
Object o = `` my string '' ; Console.WriteLine ( o.GetType ( ) ) ; System.String
How does GetType ( ) knows the type of a derived class ?
C#
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 , now whe...
class Checks { public Checks ( string hostname2 ) { // logic here when class loads } public void Testing ( ) { MessageBox.Show ( hostname2 ) ; } }
Using strings from other classes C #
C#
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 and be done ...
10,10,20,20,30,35,40,50,45,50,45,50,50,50,20,20,45,90,85,85 int [ 10 ] earned = { 10,20,30,40,45,50,20,45,85 } ; int [ 10 ] possible = { 10,20,35,50,50,50,20,90,85 } ; for ( x=0 ; x < 10 ; x++ ) { earned [ x ] = scores [ x*2 ] poss [ x ] = scores [ ( x*2 ) +1 ] }
How to populate two separate arrays from one comma-delimited list ?
C#
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 like this :...
public class Recipe { [ Required ] public virtual Food Food { get ; set ; } // ... rest } public class Recipe { public virtual IList < Food > Foods { get ; set ; } // ... rest } public class Recipe { [ Required ] public virtual Food Food { get ; set ; } public virtual IList < Food > Foods { get ; set ; } // ... rest } ...
Moving items to list of items in an Entity Framework migration
C#
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. -- Edit -- When ...
class Program { static void Main ( string [ ] args ) { Foobar foobar = new Foobar ( ) ; Console.WriteLine ( foobar.foo ) ; // Outputs `` Hello '' Console.WriteLine ( Foobar.bar ) ; // Outputs `` Hello '' var field = foobar.GetType ( ) .GetField ( `` foo '' ) ; field.SetValue ( foobar , `` World '' ) ; // Ok field = foo...
Why is it possible to change the value of a readonly field but not of a const using reflection ?
C#
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 between obj...
public ActionResult Customer ( PurchaseViewModel purchaseviewmodel ) { TempData [ `` Fromdt '' ] = purchaseviewmodel.FromDate ; TempData [ `` todt '' ] = purchaseviewmodel.ToDate ; If ( TempData [ `` Fromdt '' ] == Convert.ToDateTime ( “ 01/01/0001 ” ) & & TempData [ `` todt '' ] == Convert.ToDateTime ( “ 01/01/0001 ” ...
Is it possible to check TempData inside if condtion in Asp.Net MVC ?
C#
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 ( ) at some ...
public virtual void Close ( ) { if ( ! IsOpen ) return ; Dispose ( ) ; RaiseClosed ( ) ; }
How can I enforce derived methods to follow a certain pattern ?
C#
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 .
enum ValueType : int { FloatingPoint = 2 , ... / ... } enum ConstraintType : int { Range = 2 , ... / ... } enum Parameter : int { ExposureTime = F ( ValueType.FloatingPoint , ConstraintType.Range , 23 ) , ... / ... } private static int F ( ValueType _V , ConstraintType _C , int _N ) { ... } private static int F ( int _...
Values of enum as result of a function
C#
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 sealed IDisp...
DbCommand CreateCommandUnsafely ( string commandText ) { var newCommand = connection.CreateCommand ( ) ; newCommand.CommandText = commandText ; //what if this throws ? return newCommand ; } DbCommand CreateCommandSafelyA ( string commandText ) { DbCommand newCommand = null ; bool success = false ; try { newCommand = co...
What 's the best way of returning constructed IDisposables safely ?
C#
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 would be : ...
T best ; float bestFit = something very low ; foreach ( T ob in collection ) { float fit = FitFunction ( ob ) ; if ( fit > bestFit ) { bestFit = fit ; best = ob ; } } return best ;
How to do a 'search a take best ' function in LINQ ?
C#
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 must retur...
static class Extensions { public static Func < T > AsDelegate < T > ( this T value ) { return ( ) = > value ; } } class Program { static void Main ( string [ ] args ) { new Program ( ) ; } Program ( ) { double x = Math.PI ; Func < double > ff = x.AsDelegate ( ) ; Func < double > fg = ( ) = > x ; x = -Math.PI ; double y...
Why do these two functions not return the same value ?
C#
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 third element...
string message = File.ReadAllText ( @ '' C : \Temp\SomeReport.txt '' ) .Substring ( 411 , 3 ) ; if ( message == `` Ok ; '' ) // ` ; ` character should be removed in case that Ok is fetched { message = `` Ok '' ; }
most elegant way to remove string element
C#
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 is not a g...
enum MyEnum { aaaVal1 , aaaVal2 , aaaVal3 , } string translate ( MyEnum myEnum ) { string result = `` '' ; switch ( ( int ) myEnum ) { 0 : result = `` abc '' ; 1 : result = `` dft '' ; default : result = `` fsdfds '' } return result ; }
Enum item mapped to another value
C#
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 ?
string temp ; if ( obj== null ) { temp = `` OK '' ; } string final = temp ;
Why assign value to string before comparing , when default is null
C#
I have the following code : Why does it only throw one exception when multiple errors are in the list ?
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#
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 probably come up...
int a = 1 , b , c , d ; if ( a > 0 || b > 1 || c > 2 || d > 3 ) { //do stuff }
C # How to check which part of an if statement is correct
C#
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 the Exten...
Derived derived = new Derived ( ) ; derived.Count ( ) ; //Base classpublic class Base { public virtual string Count ( ) { return string.Empty ; } } //Derived classpublic class Derived : Base { public override string Count ( ) { return base.Count ( ) ; } } //Extension Methods for Derived classpublic static class Extensi...
Why Extension Method behaves different ?
C#
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 ?
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#
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 , creating a ...
CreateUser ( ) { CreateUserFtpAccount ( ) ; CreateUserFolder ( ) ; SetUserPermission ( ) ; CreateVirtualDirectoryForUser ( ) ; ... . ... . ... . and many more }
How to ensure that a system level operation is atomic ? any pattern ?
C#
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
if ( Extender.GetSetting < string > ( `` User '' ) == null ) { ConfigureApp ( ) ; } else { loadUser ( ) ; } Extender.GetSettings < string > ( `` User '' ) ? ? ConfigureApp ( ) : loadUser ( ) ; Extender.GetSettings < string > ( `` User '' ) == null ? ConfigureApp ( ) : loadUser ( ) ;
Fast/Easy way to run a method based on a condition