lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have the following problem : After I add a string to my number the second digit after the point disappears like thisThe output is 37,4 when it should be 37,40 with one more digit after the comma . How do I fix this problem ? When I print it without adding the last piece of string the output of the integer is correct ...
var needed_product = sets * ( 2 * price_bananas ) + sets * ( 4 * price_eggs ) + sets * ( 0.2 * price_berries ) ; var difference = Math.Abs ( needed_product - amount_cash ) ; if ( amount_cash > =needed_product ) { Console.Write ( `` Ivancho has enough money - it would cost `` + `` { 0 : F2 } '' , needed_product + `` lv ...
C # Numbers after decimal disappear after I join them with a string
C#
What 's a good collection in C # to store the data below : I have check boxes that bring in a subjectId , varnumber , varname , and title associated with each checkbox.I need a collection that can be any size , something like ArrayList maybe with maybe : Any good ideas ?
list [ i ] [ subjectid ] = x ; list [ i ] [ varnumber ] = x ; list [ i ] [ varname ] = x ; list [ i ] [ title ] = x ;
A Good C # Collection
C#
Let 's say we have a project that will handle lots of data ( employees , schedules , calendars ... .and lots more ) . Client is Windows App , Server side is WCF . Database is MS SQL Server . I am confused regarding which approach to use . I read few articles and blogs they all seem nice but I am confused . I do n't wan...
// classes that hold datapublic class Employee { public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } ... .. } public class Assignment { public int Id { get ; set ; } public int UserId { get ; set ; } public DateTime Date { get ; set ; } ... .. } ... .. public sta...
which design is better for a client/server project with lots of data sharing
C#
Have Have How can I search lbyte for not just a single byte but for the index of the searchBytes ? E.G.Here is the brute force I came up with.Not the performance I am looking for .
List < byte > lbyte byte [ ] searchBytes Int32 index = lbyte.FirstIndexOf ( searchBytes ) ; public static Int32 ListIndexOfArray ( List < byte > lb , byte [ ] sbs ) { if ( sbs == null ) return -1 ; if ( sbs.Length == 0 ) return -1 ; if ( sbs.Length > 8 ) return -1 ; if ( sbs.Length == 1 ) return lb.FirstOrDefault ( x =...
Search for an Array or List in a List
C#
Consider the following code : As expected , the non-generic DoSomething method will be invoked . Now consider the following modification : The only thing I 've changed is adding the T type parameter to the second overload , thus making it generic . Note that the type parameter is not used.That modification causes the f...
public class Tests { public void Test ( ) { Assert.AreEqual ( `` Int '' , DoSomething ( 1 ) ) ; } public static string DoSomething < T > ( T value ) { return `` Generic '' ; } public static string DoSomething ( int value ) { return `` Int '' ; } } public class Tests { public void Test ( ) { Assert.AreEqual ( `` Int '' ...
Generic Method Resolution
C#
How can I generate types like these using the System.Reflection.Emit libraries : When I call ModuleBuilder.DefineType ( string ) with the second type declaration , I get an exception because there is already another type in the module with the same name ( I 've already defined the type parameter on the first type ) . A...
public class Test < T > { } public class Test < T1 , T2 > { }
How can I define multiple types with the same name and different type parameters using Reflection Emit ?
C#
I have a collection of first names which I need to combine into a comma separated string.The generated string needs to adhere to proper grammar.If the collection contains one name , then the output should be just that name : If the collection contains two names , then the output should be separated by the word `` and '...
John John and Mary John , Mary , and Jane List < string > firstNames = new List < string > ( ) ; firstNames.Add ( `` John '' ) ; firstNames.Add ( `` Mary '' ) ; firstNames.Add ( `` Jane '' ) ; string names = string.Empty ; for ( int i = 0 ; i < firstNames.Count ; i++ ) { if ( i == 1 & & firstNames.Count == 2 ) { names ...
How to Build String from a Collection of Names
C#
As you all know , in C # we could not do something like this : ororBut this code compiles successfully and in debug mode I can see that type of the voidObject is System.Void : What is this ? Is this real instance of void ?
var voidObject = new void ( ) ; var voidObject = new System.Void ( ) ; var voidObject = Activator.CreateInstance ( typeof ( void ) ) ; var voidObject = FormatterServices.GetUninitializedObject ( typeof ( void ) ) ;
Did I instantiate an object of void ?
C#
Does someone have a script or snippet for Visual Studio that automatically removes comment headers for functions or classes ? I want to remove comments like.Actually anything that removes comments starting with /// would really help . We have projects with massive amount of GhostDoc comment that really just hides the c...
/// < summary > /// /// < /summary >
How can I automate the removal of XML Documentation Comments ?
C#
I 'm having this really weird problem with a conditional statement when setting an Action < T > value . It 's not that I do n't know how to work around this as it 's pretty easy to solve by using a normal if.Here 's my problem : This gives me a compiler error with the message There 's no implicit conversion between 'me...
public class Test { public bool Foo { get ; set ; } public Action < bool > Action { get ; set ; } public void A ( ) { Action = Foo ? B : C ; //Gives compiler error } public void B ( bool value ) { } public void C ( bool value ) { } } public void A ( ) { Action = Foo ? ( Action < bool > ) B : C ; }
Conditional statement , generic delegate unnecessary cast
C#
I am confusing about using == in ( c # ) when I use literal string like here : the comparison a==b will be true.but when I use object like here : the comparison a==b will be false.even though a , b , c , d all of type System.Object in compile time and == operator compare values depends on their values in compile time.I...
object a= '' hello '' ; object b= '' hello '' ; object c=new StringBuilder ( `` hello '' ) .ToString ( ) ; object d=new StringBuilder ( `` hello '' ) .ToString ( ) ; public static class MiscExtensions { public static Type GetCompileTimeType < T > ( this T dummy ) { return typeof ( T ) ; } }
confusing of using == operator in c #
C#
Regex is on string 's only , but what if that functionality can be extended to not only character but objects or even further to functions ? Suppose our object 's will be integers , they can be in any order : And the task you want to solve is to find prime pairs ( or similar pattern search task ) like this : So the ans...
1 2 3 4 5 6 7 8 9 10 11 12 13 { prime } { anyNumber } { prime } ( 3,4,5 ) ( 5,6,7 ) ( 11,12,13 ) { prime } ( { anyNumber } { prime } ) + ( 3 , ( 4,5 ) , ( 6,7 ) ) ( 11 , ( 12,13 ) ) char this [ int index ] { get ; }
How to search patterns in arbitrary sequences ?
C#
I 'm trying to normalize arbitrary chains of .Skip ( ) and .Take ( ) calls to a single .Skip ( ) call followed by an optional single .Take ( ) call.Here are some examples of expected results , but I 'm not sure if these are correct : Can anyone confirm these are the correct results to be expected ? Here is the basic al...
.Skip ( 5 ) = > .Skip ( 5 ) .Take ( 7 ) = > .Skip ( 0 ) .Take ( 7 ) .Skip ( 5 ) .Skip ( 7 ) = > .Skip ( 12 ) .Skip ( 5 ) .Take ( 7 ) = > .Skip ( 5 ) .Take ( 7 ) .Take ( 7 ) .Skip ( 5 ) = > .Skip ( 5 ) .Take ( 2 ) .Take ( 5 ) .Take ( 7 ) = > .Skip ( 0 ) .Take ( 5 ) .Skip ( 5 ) .Skip ( 7 ) .Skip ( 11 ) = > .Skip ( 23 ) ....
Normalizing chains of .Skip ( ) and .Take ( ) calls
C#
I was just working on some code and caught myself making this errorobviously this is wrong and should be but it just got me thinking in regards to readability would the first be easier ? Maybe having some logic that could say unless a new stringName is specified , use the first one ? Really not a question , Im just cur...
if ( stringName == `` firstName '' || `` lastName '' ) // Do code if ( stringName == `` firstName '' || stringName == `` lastName '' ) // Do code
C # Operators and readability
C#
I 've started to use a define class like so : The advantages I see is : Ensures I do n't break stuff that with an # if.. # else.. # endif would not be checked by compiler.I can do a find references to see where it is used.It 's often useful to have a bool for debug , defines code is longer/more messy.Possible disadvant...
internal sealed class Defines { /// < summary > /// This constant is set to true iff the define DEBUG is set . /// < /summary > public const bool Debug = # if DEBUG true ; # else false ; # endif } private readonly Permissions _permissions = Defines.Debug ? Permissions.NewAllTrue ( ) : Permissions.NewAllFalse ( ) ; var ...
Defines.Debug vs # if DEBUG
C#
I have a method which compares two nullable ints and prints the result of the comparison to the console : And this is the result of its decompilation : The result is more or less what I expected but I wonder why the non-short-circuit version of the logical 'and ' operator ( & ) is used instead of the short-circuit vers...
static void TestMethod ( int ? i1 , int ? i2 ) { Console.WriteLine ( i1 == i2 ) ; } private static void TestMethod ( int ? i1 , int ? i2 ) { int ? nullable = i1 ; int ? nullable2 = i2 ; Console.WriteLine ( ( nullable.GetValueOrDefault ( ) == nullable2.GetValueOrDefault ( ) ) & ( nullable.HasValue == nullable2.HasValue ...
Why is the short-circuit logical 'and ' operator not used when comparing two nullables for equality ?
C#
When I execute an update on my SQL Server database , I get a result of the rows affected by the update AND the affected rows of some triggers.So for example , an update executed directly on database : Now when I execute _context.Database.ExecuteSqlCommand ( query , params ) I always get the sum of all those results , i...
UPDATE : ( 32 row ( s ) affected ) Trigger1 : ( 1 row ( s ) affected ) Trigger2 : ( 2 row ( s ) affected ) ...
Get only result of update query
C#
While modelling my domain classes , I found that Entity Framework lets you model inheritance relationships , but does n't support promoting a base type instance to its derived type , i.e . changing an existing Person row in the database to an Employee , which derives from Person.Apparently , I was n't the first to wond...
public class Person { public string Name { get ; set ; } } public class Employee : Person { public int EmployeeNr { get ; set ; } public decimal Salary { get ; set ; } } public class Person { public string Name { get ; set ; } public EmployeeInfo EmployeeInfo { get ; set ; } } public class EmployeeInfo { public int Emp...
Inheritance : why is changing an object 's type considered bad design ?
C#
It 's an asp.net core webapi project , and I simply put the [ Authorize ] attribute to protect those apis . If user is not authorized , the api will return `` 401 unauthorized '' . My question is how can I localize the `` 401 unauthorized '' message if unauthorized.For other data annotations , I can set the ErrorMessag...
using System ; using System.Threading.Tasks ; using YourNamespace.Messages ; using Microsoft.AspNetCore.Authorization ; using Microsoft.AspNetCore.Http ; using Microsoft.AspNetCore.Mvc ; using Microsoft.AspNetCore.Mvc.Filters ; using Microsoft.Extensions.DependencyInjection ; using Microsoft.Extensions.Localization ; u...
How to localize the error message if unauthorized
C#
Why c=-2always ? I have checked in loop also . Its seems garbage value but why -2 only ?
int a = int.MaxValue ; int b = int.MaxValue ; int c = a + b ;
Why int.Max+ int.Max = -2
C#
After my last , failed , attempt at asking a question here I 'm trying a more precise question this time : What I have : A huge dataset ( finite , but I wasted days of multi-core processing time to compute it before ... ) of ISet < Point > .A list of input values between 0 to 2n , n≤17What I need:3 ) A table of [ 1 ] ,...
new List < ISet < Point > > ( ) { new HashSet ( ) { new Point ( 0,0 ) } , new HashSet ( ) { new Point ( 0,0 ) , new Point ( 2,1 ) } , new HashSet ( ) { new Point ( 0,1 ) , new Point ( 3,1 ) } } A B C D E F1234567 A B C D E F1 - C A E - -2 B C E F A -3 ... ... ... ... ... .4 ... ... ... ... ... .5 ... ... ... ... ... .6...
Improving set comparisons by hashing them ( being overly clever.. ? )
C#
I 've created an Interface like so : However , when I implement the interface in a class , I have to define the CloneTo method also using T as the type as follows : This does compile and run . However , it 's not ideal as I could pass any other item that implements ICacheable to the method where I only want to be able ...
public interface ICacheable { void CloneTo < T > ( T entity ) where T : class , new ( ) ; } public class MyEntity : ICacheable { public void CloneTo < T > ( T genericEntity ) where T : class , new ( ) { } } public class MyEntity : ICacheable { public void CloneTo ( MyEntity entity ) { } } public interface ICacheable < ...
c # interface with method < T > but implement as concreate
C#
I want to get the mac address of my software user on the network due to some security reasons . But i am able to get the mac address of the router through following method.I need the specific mac address of the system that access my software on the internet and the internal device of that router . is that possible thro...
public string GetMACAddress ( ) { NetworkInterface [ ] nics = NetworkInterface.GetAllNetworkInterfaces ( ) ; String sMacAddress = string.Empty ; foreach ( NetworkInterface adapter in nics ) { if ( sMacAddress == String.Empty ) // only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIP...
In C # how to find the mac address of internal devices not the Router mac address
C#
I 'm looking for the fastest way to create scaled down bitmap that honors EXIF orientation tagRef : https : //weblogs.asp.net/bleroy/the-fastest-way-to-resize-images-from-asp-net-and-it-s-more-supported-ishCurrently i use the following code to create a Bitmap that honors EXIF Orientation tagI 'm first creating a orient...
static Bitmap FixImageOrientation ( Bitmap srce ) { const int ExifOrientationId = 0x112 ; // Read orientation tag if ( ! srce.PropertyIdList.Contains ( ExifOrientationId ) ) return srce ; var prop = srce.GetPropertyItem ( ExifOrientationId ) ; var orient = BitConverter.ToInt16 ( prop.Value , 0 ) ; // Force value to 1 p...
Using WIC to Quickly Create Scaled Down Bitmap that honors EXIF Orientation Tag
C#
Background : In an attribute specification , there is sometimes two valid ways to write the applied attribute . For example , if an attribute class has the name HorseAttribute , you can apply the attribute as either [ HorseAttribute ] or just [ Horse ] . Ambiguities can be resolved with a @ , for example [ @ Horse ] .T...
using System ; using Alpha ; using Beta ; namespace N { [ Horse ] class C { } } namespace Alpha { // valid non-abstract attribute type with accessible constructor class HorseAttribute : Attribute { } } namespace Beta { // any non-attribute type with that name enum Horse { } } using System ; using Alpha ; using Beta ; n...
Curious ambiguity in attribute specification ( two using directives )
C#
Using C # and Regex I have a strange situation : In my world the above would give me a result in 'collection ' that contains 6 results . Strangly enough my collection contains 12 results and every second result is { } ( empty ) .I have tried rewriting it to : But it gives me the exact same result . What am I missing he...
string substr = `` 9074552545,9075420530,9075662235,9075662236,9075952311,9076246645 '' ; MatchCollection collection = Regex.Matches ( substr , @ '' [ \d ] * '' ) ; string substr = `` 9074552545,9075420530,9075662235,9075662236,9075952311,9076246645 '' ; Regex regex = new Regex ( @ '' [ \d ] * '' ) ; MatchCollection co...
Regex MatchCollection gets too many results
C#
C # ensures that certain types always have atomic reads and writes . Do I have those same assurances when calling Array.Copy on two arrays of those types ? Is each element atomically read and written ? I browsed some of the source code but did not come away with a solid answer.For example , if I rolled my own code for ...
static void Copy < T > ( T [ ] source , T [ ] destination , int length ) { for ( int i = 0 ; i < length ; ++i ) destination [ i ] = source [ i ] ; }
Does Array.Copy maintain the guarantee about atomic reads and writes on a per element basis ?
C#
I have two interfaces with same method and in my main class The compiler doesnt give any error and the result is displayed..Is it right ? ? should n't we use FirstInterface.add ? ? does it mean interfaces are resolved at compile time ? ?
interface FirstInterface { int add ( int x , int y ) ; } interface SecondInterface { int add ( int x , int y ) ; } class TestInterface : FirstInterface , SecondInterface { public TestInterface ( ) { } public int add ( int x , int y ) { return x + y ; } } static void Main ( string [ ] args ) { TestInterface t = new Test...
Multiple Interface inheritance in C #
C#
I have aproblem with the order of static variable declaration in C # When i run this code : The output is : But when i change the static variable declaration order like this : The Output is : Why this happend ?
static class Program { private static int v1 = 15 ; private static int v2 = v1 ; static void Main ( string [ ] args ) { Console.WriteLine ( `` v2 = `` +v2 ) ; } } v2=15 static class Program { private static int v2 = v1 ; private static int v1 = 15 ; static void Main ( string [ ] args ) { Console.WriteLine ( `` v2 = `` ...
Static variable order
C#
I have this if else statement which is assigned to compare results from a text box to a list of context . I am wondering how do i make it such that it is case insensitive ?
value = textbox1.Text ; if ( article.contains ( value ) ) { label = qwerty ; } else { break ; {
c # If else statement with case insensative
C#
I have an ObservableCollection which is the DataContext for a Grid . The Grid is a User Control inserted into the main Window.I would like to display 'Record x of y ' in the StatusBar so , as a first step , I am attempting to display it in the Grid using this XAML : The Count works without issue , and updates automatic...
< TextBlock Grid.Row= '' 2 '' Grid.Column= '' 3 '' > < TextBlock Text= '' { Binding CurrentPosition } '' / > < TextBlock Text= '' { Binding Count } '' / > < /TextBlock > public MyObservableCollection ( ) : base ( ) { this.GetDefaultView ( ) .CurrentChanged += MyObservableCollection_CurrentChanged ; } using System ; usi...
StatusBar record x of y
C#
I 'm using a RIA Services DomainContext in a Silverlight 4 app to load data . If I 'm using the context from the UI thread , is the callback always going to be on the UI thread ? Or put another way , is the callback always on the same thread as the call ? Some example code below illustrating the scenario ...
private void LoadStuff ( ) { MyDomainContext context = new MyDomainContext ( ) ; context.Load ( context.GetStuffQuery ( ) , op = > { if ( ! op.HasError ) { // Use data . // Which thread am I on ? } else { op.MarkErrorAsHandled ( ) ; // Do error handling } } , null ) ; }
Which thread is the callback executing on when performing an asynchronous RIA Services call ?
C#
I 'm getting an error incorrect syntax near the keyword WHEREwith the following SQL statement : What 's wrong ?
SqlCommand scInsertCostSpilt = new SqlCommand ( `` INSERT INTO [ ASSETS_CC ] ( [ DEPT ] , [ CC ] , [ PER_CENT ] ) WHERE [ ASSET_NO ] = @ AssetNumber ) '' + '' Values ( @ AssetNumber , @ Dept , @ CC , @ PerCent ) '' , DataAccess.AssetConnection ) ;
SQL query : Incorrect Syntax error
C#
I have a list which is declared below , at the start I default the list items to { -1 , - } . please note that throughout the program the list size is fixed at 2.My question is regarding , what would be the best approach if I need to overwrite the two values in the list.Approach 1 : Approach 2 : What would be a better ...
List < int > list = new List < int > ( new int [ ] { -1 , -1 } ) ; int x = GetXValue ( ) ; int y = GetYValue ( ) ; list = new List < int > ( new int [ ] { x , y } ) ; list [ 0 ] = x ; list [ 1 ] = y ;
.NET List best approach
C#
Out of curiosity I wanted to test the number of ticks to compare a GenericList against an ArrayList.And for the below code when I check the stopwatches , ArrayList seems to faster.Do I make something wrong or is there an explanation for this ? ( I believed List sto be much faster ) Tesing Code and the output below :
private static void ArrayListVsGenericList ( ) { // Measure for ArrayList Stopwatch w0 = new Stopwatch ( ) ; w0.Start ( ) ; ArrayList aList = new ArrayList ( ) ; for ( int i = 0 ; i < 1001 ; i++ ) { Point p = new Point ( ) ; p.X = p.Y = i ; aList.Add ( p ) ; } foreach ( Point point in aList ) { int v0 = ( ( Point ) aLi...
Why does a simple List < T > seem to be slower than an ArrayList ?
C#
I have a struct TimePoint which is similar to a Point except , the x value is a datetime , an observable collection of these timepoints and a method that takes a datetime and returns a double value.I want to retrieve the max and min value of the doubles that are returned from the datetimesin this collection.I am new to...
double minDouble = 0 ; double maxDouble = 0 ; foreach ( TimePoint item in obsColl ) { var doubleVal = ConvertToDouble ( item.X ) ; //Here x is a datetime if ( minDouble > doubleVal ) minDouble = doubleVal ; if ( maxDouble < doubleVal ) maxDouble = doubleVal ; }
LINQ - C # - Using lambda - Get a set of data from a Collection
C#
Given : Why can I write : But not : Which gives me the following warning : Error 29 Can not implicitly convert type 'MyApp.MyNS.MyStruct [ ] ' to 'System.Collections.Generic.IEnumerable < MyApp.MyNS.IMyInterface > 'And must instead be written :
public interface IMyInterface { } public class MyClass : IMyInterface { public MyClass ( ) { } } public struct MyStruct : IMyInterface { private int _myField ; public MyStruct ( int myField ) { _myField = myField ; } } IEnumerable < IMyInterface > myClassImps = new [ ] { new MyClass ( ) , new MyClass ( ) , new MyClass ...
IEnumerable < IMyInterface > Implicitly From Class [ ] But Not From Struct [ ] . Why ?
C#
Given this `` IHandle '' interface and two classes to be handled : I want to create a generic base that takes care of `` resetting '' as well as managing M1 instances : This does not compile since the compiler believes T could be `` MReset '' so it outputs : error CS0695 : 'HandlerBase ' can not implement both 'IHandle...
interface IHandle < T > { void Handle ( T m ) ; } class M1 { public int Id ; } class MReset { } class HandlerBase < T > : IHandle < MReset > , IHandle < T > where T : M1 { protected int Count ; void IHandle < T > .Handle ( T m ) { ++Count ; Console.WriteLine ( `` { 0 } : Count = { 0 } '' , m.Id , Count ) ; } void IHand...
Odd C # behavior when implementing generic interface
C#
Possible Duplicate : C # okay with comparing value types to null Why does C # allow : Resharper says `` expression is always false '' - which is obviously - true since MyInt is int and not int ? But how C # allow this to compile ? The property will always be there and its type is int !
class MyClass { public int MyInt ; } static void Main ( string [ ] args ) { MyClass m = new MyClass ( ) ; if ( m.MyInt == null ) // < -- -- -- -- -- -- - ? Console.Write ( `` ... ... '' ) ; }
Why does c # allow this ? ( null checking to int )
C#
Checking in C # a VB.NET object for null gives unexpected compile error : Resharper 's suggested fix : I have a colleague that have done this in a year without any problems . My colleague is using Visual Studio 2012 and I 'm using Visual Studio 2013.Could it be some kind of a settings ? Why is basePackage ! = null an o...
// Can not compile : var basePackage = BasePackage.GetFromID ( id ) ; // GetFromID is from VB.NETif ( basePackage ! = null ) // Errormesage : `` Can not implicitly convert 'object ' to 'bool ' { } // Can compileif ( ( bool ) ( basePackage ! = null ) ) { linkedGroups = basePackage.GetLinkedGroups ( ) ; } Public Shared O...
Checking in C # a VB.NET object for null gives unexpected compile error
C#
When I tried a sample expression in C # in Visual StudioWhen I keep the expression 10/2 == 5 , the vs.net automatically throws a warning `` Unreachable Code Detected '' .If I change the expression 10/2 == 6 , the IDE is happy ? How does it happen ? Edited : Sorry for the incomplete question . It happens so instantly an...
public int Test ( ) { if ( 10/2 == 5 ) throw new Exception ( ) ; return 0 ; }
Evaluation of C # constant expression by VS.NET 2010
C#
Is there a way to tell ReSharper to use the String and Int64 type names when a field or method is used on the type ( 'static-ally ' ) , but string and long for variable initialization ? Examples :
string name = `` @ user '' ; // butint compResult = String.Compare ( a , b , ... ) ; long x = 0 ; // butlong x = Int64.Parse ( s ) ;
ReSharper Code Cleanup
C#
Ok - I have someone I work with who has written somthing like thisI dont like this ! ! If there are ten different boolean flags how many combinations are there ? 10 factorial ? I am trying to explain why this is bad
if ( ) if ( ) if ( ) if ( ) if ( )
How Many Combinations In This If Statement
C#
I would like to know what are the differences between those two linq statements ? What is faster ? Are they the same ? What is the difference between this statementand this statement ? Thanks in advance guys.EDIT : In context of LINQ to Objects
from c in categoriesfrom p in productswhere c.cid == p.pidselect new { c.cname , p.pname } ; from c in categoriesjoin p in products on c.cid equals p.pidselect new { c.cname , p.pname } ;
Linq To Objects - Under The Hood Of Joins
C#
In my extension that I am writing for Visual Studio 2015 I want to change the tab size and indent size as at work we have a different setting as when I am developing for opensource project ( company history dating our C period ) . I have written the following code in my command class : When testing in an experimental h...
private const string CollectionPath = @ '' Text Editor\CSharp '' ; private void MenuItemCallback ( object sender , EventArgs e ) { var settingsManager = new ShellSettingsManager ( ServiceProvider ) ; var settingsStore = settingsManager.GetWritableSettingsStore ( SettingsScope.UserSettings ) ; var tabSize = settingsStor...
Writing Visual Studio settings in an extension do not stay
C#
Consider the following XamlIt will set theText Property of a TextBox ( only WPF ) Content Property of a ButtonChildren Property of a GridBut how is this specified ? How do you specify which Property that goes between the opening and closing tag in Xaml ? Is this set by some metadata in the Dependency Property or what ?...
< Grid > < TextBox > Text < /TextBox > < Button > Content < /Button > < /Grid >
Specify which Property goes between the opening and closing tag in Xaml
C#
I have a SOAP web service which I am pulling various information from . Most functions are working correctly , but I need some functions to return a List.The WebMethod is defined like : The web service is referenced in the main project and is called by : client_GetAllMyTypesCompleted is defined as : It is here that the...
List < MyType > myTypes = new List < MyTypes > ( ) ; [ WebMethod ] public List < MyType > GetAllMyTypes ( ) { string sql = `` SELECT * FROM MyType '' ; DataTable dt = new DataTable ( ) ; dt = Globals.GLS_DataQuery ( sql ) ; List < MyType > myType = new List < MyType > ( ) ; foreach ( DataRow row in dt.Rows ) { MyType m...
TargetInvocationException when retrieving list from SOAP web service in Azure
C#
Noticed MongoDB has different keywords , like InsertOne , ReplaceOne , etc.A point of Linq ( Language Integrated Query ) , was to have a universal language where people can utilize dependency injection and swap between SQL or NoSQL without changing syntax heavily . SQL uses .Add ( ) and Remove ( ) .Is there an easy way...
public BookService ( IConfiguration config ) { var client = new MongoClient ( config.GetConnectionString ( `` BookstoreDb '' ) ) ; var database = client.GetDatabase ( `` BookstoreDb '' ) ; _books = database.GetCollection < Book > ( `` Books '' ) ; } public List < Book > Get ( ) { return _books.Find ( book = > true ) .T...
Use Same Syntax for MongoDB and SQL with C # or Linq
C#
I am using WebClient to try and get a string response from a piece of hardware connected locally to my PC . My PC has a network adaptor connected to a LAN and a second adaptor that is connected only to my piece of hardware.If I use IE with the URL : http : //169.254.103.127/set.cmd ? user=admin+pass=12345678+cmd=getpow...
using ( WebClient client = new WebClient ( ) ) { client.Proxy = WebRequest.DefaultWebProxy ; client.Credentials = CredentialCache.DefaultCredentials ; client.Proxy.Credentials = CredentialCache.DefaultCredentials ; client.Headers [ `` User-Agent '' ] = `` Mozilla/4.0 ( Compatible ; Windows NT 5.1 ; MSIE 6.0 ) `` + `` (...
WebClient and multiple network adaptors
C#
I 'm trying to automate some stuff on a legacy application that I do n't have the source to . So I 'm essentially trying to use the Windows API to click the buttons I 'll need on it.There is a toolbar of type msvb_lib_toolbar that looks like this : I can get a handle to it ( I think ) by using this code : Looking at th...
IntPtr window = FindWindow ( `` ThunderRT6FormDC '' , `` redacted '' ) ; IntPtr bar = FindWindowEx ( window , IntPtr.Zero , '' msvb_lib_toolbar '' , null ) ; [ DllImport ( `` user32.dll '' ) ] public static extern int SendMessage ( int hWnd , uint Msg , int wParam , int lParam ) ; AutomationElement mainWindow = Automat...
Click Button in Toolbar of Other Program
C#
For me it looks quite strange , and like a bug.This code in Release mode in Visual Studio 2019 provides infinite loop.volatile or Thread.MemoryBarrier ( ) ; ( after _a = 0 ; ) solves the issue . Do n't think I had such issue with VS2015 . Is this correct behavior ? What exact part is optimized ?
class Program { private static int _a ; static void Main ( string [ ] args ) { _a = 1 ; while ( _a == 1 ) { Console.WriteLine ( _a ) ; _a = 0 ; } } }
VS 2019 optimize code in release mode broken ?
C#
I 've built an event system that maintains a dictionary of delegates , adds/removes elements to this dictionary via generic Subscribe/Unsubscribe methods ( which each take an Action of type T ) , and has a Publish method to notify the subscribers when something happens ( which also takes an Action of type T ) . Everyth...
private readonly Dictionary < Type , Delegate > delegates = new Dictionary < Type , Delegate > ( ) ; public void Subscribe < T > ( Action < T > del ) { if ( delegates.ContainsKey ( typeof ( T ) ) ) { // This does n't work ! delegates [ typeof ( T ) ] += del as Delegate ; // This does n't work ! delegates [ typeof ( T )...
The difference between += and Delegate.Combine
C#
Previously I have asked a question that was answered not fully , hence I have decided to re-formulate my question to understand what is going on : Here is my class hierarchy : Here is the execution code : As it is right now , it will either output A or C. It wo n't output B . Here is the question : Could you please exp...
interface I { void f ( ) ; } class A : I { // non virtual method public void f ( ) { Debug.Log ( `` -- -- > > A `` ) ; } } class B : A { // non overriding but hiding class A method public void f ( ) { Debug.Log ( `` -- -- > > B `` ) ; } } class C : I { // non virtual method public void f ( ) { Debug.Log ( `` -- -- > > ...
What function will be called ?
C#
I have read a couple of articles about the using statement to try and understand when it should be used . It sound like most people reckon it should be used as much as possible as it guarantees disposal of unused objects.Problem is that all the examples always show something like this : That makes sense , but it 's suc...
using ( SqlCommand scmFetch = new SqlCommand ( ) ) { // code } string sQuery = @ '' SELECT [ ID ] , [ Description ] FROM [ Zones ] ORDER BY [ Description ] `` ; DataTable dtZones = new DataTable ( `` Zones '' ) ; using ( SqlConnection scnFetchZones = new SqlConnection ( ) ) { scnFetchZones.ConnectionString = __sConnect...
Trying to understand the 'using ' statement better
C#
Here is a typical function that returns either true/false ; Now on an error , I would like to return my own custom error object with definition : I would have expected to be able to throw this custom object for example ... This is not possible , and I do n't want to derive Failure from System.IO.Exception because I hav...
private static bool hasValue ( ) { return true ; } public class Failure { public string FailureDateTime { get ; set ; } public string FailureReason { get ; set ; } } private static bool hasValue ( ) { try { ... do something } catch { throw new Failure ( ) ; } return true ; }
C # Possible to have a generic return type ?
C#
I have some code that relied on methods not being inlined : Of course this does only work if the DoSomething method is not inlined . This is the reason why the base class derives from MarshallByRefObject , which prevent inlining of public methods.It worked until now , but I got a stacktrace from a .Net 4 server showing...
internal class MyClass : BaseClass { // should not be inlined public void DoSomething ( int id ) { base.Execute ( id ) ; } } public abstract class BaseClass : MarshallByRefObject { [ MethodImpl ( MethodImplOptions.NoInlining ) ] protected void Execute ( params object [ ] args ) { // does a stack walk to find signature ...
Does .Net 4 inline MarshalByRefObject methods ?
C#
I know I can use AutoFixture to create an auto-mocked instance usingBut , if I want to customise the way a Person is created I have several options . One is to use BuildAnd another is to use CustomizeSo , my question is , what are the various merits and pitfalls of each approach listed above , and are there any other /...
var person = fixture.Create < Person > ( ) ; var person = fixture.Build < Person > ( ) .With ( x = > x.FirstName , `` Owain '' ) .Create ( ) ; fixture.Customize < Person > ( c = > c.With ( x = > x.FirstName , `` Owain '' ) ) ; var person = fixture.Create < Person > ( ) ;
AutoFixture Customize vs Build
C#
I would expect the last line to throw an OperationCanceledException after a second , but instead it hangs forever . Why ?
NamedPipeServerStream server=new NamedPipeServerStream ( `` aaqq '' ) ; var ct=new CancellationTokenSource ( ) ; ct.CancelAfter ( 1000 ) ; server.WaitForConnectionAsync ( ct.Token ) .Wait ( ) ;
CancellationToken not working with WaitForConnectionAsync
C#
As you see in the above code I need to convert someEnumType to byte array type before calling base class constructor . Is there a way to do it ? Something like :
public class bar { public bar ( list < int > id , String x , int size , byte [ ] bytes ) { ... } } public class Foo : Bar { public Foo ( list < int > id , String x , someEnumType y ) : base ( id , x , sizeof ( someEnumType ) , y ) { //some functionality } } public class Foo : Bar { public Foo ( list < int > id , String...
Calling a base class constructor in derived class after some code block in derived constructor
C#
I 'm trying to write a quicksort for my own edification . I 'm using the pseudocode on wikipedia as a guide . My code works . It seems like it should run in O ( n log n ) time . I tried actually timing my code to check the complexity ( i.e. , when I double the input size , does the run time increase by approximately n ...
public static void QuickSortInPlace ( int [ ] arr ) { QuickSortInPlace ( arr , 0 , arr.Length - 1 ) ; } private static void QuickSortInPlace ( int [ ] arr , int left , int right ) { if ( left < right ) { //move the middle int to the beginning and use it as the pivot Swap ( arr , left , ( left + right ) / 2 ) ; int pivo...
Is This a QuickSort ?
C#
I 'm pretty familiar with the async/await pattern , but I 'm bumping into some behavior that strikes me as odd . I 'm sure there 's a perfectly valid reason why it 's happening , and I 'd love to understand the behavior.The background here is that I 'm developing a Windows Store app , and since I 'm a cautious , consci...
public static class TestHelpers { // There 's no ExpectedExceptionAttribute for Windows Store apps ! Why must Microsoft make my life so hard ? ! public static void AssertThrowsExpectedException < T > ( this Action a ) where T : Exception { try { a ( ) ; } catch ( T ) { return ; } Assert.Fail ( `` The expected exception...
Unexpected behavior when passing async Actions around
C#
Currently I 'm working with some libraries applying deferred execution via iterators . In some situations I have the need to `` forward '' the recieved iterator simply . I.e . I have to get the IEnumerable < T > instance from the called method and return it immediately.Now my question : Is there a relevant difference b...
IEnumerable < int > GetByReturn ( ) { return GetIterator ( ) ; // GetIterator ( ) returns IEnumerable < int > } // or : IEnumerable < int > GetByReYielding ( ) { for ( var item in GetIterator ( ) ) // GetIterator ( ) returns IEnumerable < int > { yield return item ; } }
What is the exact difference between returning an IEnumerable instance and the yield return statement in C #
C#
I have an array of lists : I want to extract all elements that are common in at least 2 lists . So for this example , I should get all elements [ `` a '' , `` b '' , `` c '' , `` d '' ] . I know how to find elements common to all but could n't think of any way to solve this problem .
var stringLists = new List < string > [ ] { new List < string > ( ) { `` a '' , `` b '' , `` c '' } , new List < string > ( ) { `` d '' , `` b '' , `` c '' } , new List < string > ( ) { `` a '' , `` d '' , `` c '' } } ;
how to find members that exist in at least two lists in a list of lists
C#
Is there another way of declaring my ProductController for the logger that is being injected ? Thank you , Stephen
public class ProductController : Controller { private readonly LoggingInterface.ILogger < ProductController > _logger ; private readonly IProductRepository _productRepository ; public ProductController ( LoggingInterface.ILogger < ProductController > logger , IProductRepository productRepository ) { _logger = logger ; ...
How to infer the type of an object and use that type in a generic parameter during construction
C#
I 've been working on getting long running messages working with NServiceBus on an Azure transport . Based off this document , I thought I could get away with firing off the long process in a separate thread , marking the event handler task as complete and then listening for custom OperationStarted or OperationComplete...
public abstract class LongRunningOperationHandler < TMessage > : IHandleMessages < TMessage > where TMessage : class { protected ILog _logger = > LogManager.GetLogger < LongRunningOperationHandler < TMessage > > ( ) ; public Task Handle ( TMessage message , IMessageHandlerContext context ) { var opStarted = new Operati...
NServiceBus events lost when published in separate thread
C#
I am uploading a file ( image ) using < asp : FileUpload / > and in the codebehind I use UploadedFile.SaveAs ( `` C : //Path ... '' ) to save the image on the server.This is my complete code : The problem is that it seems to reduce the quality . Here are some examples : The left image is the one I want to upload and th...
protected void btnAddImage_OnClick ( object sender , ImageClickEventArgs e ) { //_fuImage is the ID of the < asp : FileUpload / > _fuImage.SaveAs ( Server.MapPath ( fullPath ) ) ; } byte [ ] imageBytes = _fuImage.FileBytes ; File.WriteAllBytes ( Server.MapPath ( fullPath ) , imageBytes ) ;
Quality reduces after UploadedFile.SaveAs ( `` '' )
C#
Quick question about using nested disposables in a single 'using ' statement : Should I write out each disposable 's using statement , or can I nest them into one ? Example : vs.Just curious if when the block is done executing , the unnamed FileStream from `` myFile.txt '' gets cleaned up because it 's in the using sta...
using ( FileStream inFile = new FileStream ( `` myFile.txt '' , FileMode.Open ) ) using ( GZipStream gzip = new GZipStream ( inFile , CompressionMode.Decompress ) ) using ( FileStream outFile = new FileStream ( `` myNewFile.txt '' , FileMode.CreateNew ) ) { gzip.CopyTo ( outstream ) ; } using ( GZipStream gzip = new GZ...
Nesting 'IDisposable 's in a single 'using ' statement
C#
I 'm working on Unity and trying hard to make a custom SelectableButton that stores method ( s ) in two different delegates , and executes one whenever the button is selected and the other when it is deselected . The relevant part shows like that : On another script , I try to encapsulate a method in onSelect and anoth...
public delegate void OnSelectAction ( ) ; public delegate void OnDeselectAction ( ) ; public class SelectableButton : MonoBehaviour { private bool selected ; public OnSelectAction onSelect ; public OnDeselectAction onDeselect ; public bool Selected { get { return selected ; } set { selected = value ; if ( selected ) on...
Delegates for OnSelect and OnDeselect purposes
C#
gives the error : 'System.Void ' can only be used as 'typeof ' in F # butdoes not compile . Same error , `` System.Void can only be used as typeof ... '' F # void* does compilebut using it in C # throws a design-time convert error ' can not convert from 'void* ' to 'System.IntPtr'though passing the managed IntPtr will ...
[ < DllImport ( `` kernel32 '' ) > ] extern bool CloseHandle ( System.Void* handle ) ; //System.Void also throws same error //extern bool CloseHandle ( System.Void handle ) ; extern bool CloseHandle ( typeof < System.Void > handle ) ; extern bool CloseHandle ( void* handle ) ; public void CloseBeforeGarbageCollection (...
Is there a C # & VB compatible System.Void* in F # ? ( To close a pointer to nonmanaged Alloc ? )
C#
I 'm trying to implement the generic method which is intended for converting objects of Tuple < Descendant > type to objects of Tuple < Ancestor > type . I 've stuck with a problem which seems to be a limitation of the C # language.Questions : Do you have any idea how to make this code working ( take in account importa...
using System ; namespace Samples { public static class TupleExtensions { public static Tuple < SuperOfT1 > ToSuper < T1 , SuperOfT1 > ( this Tuple < T1 > target ) where T1 : SuperOfT1 { return new Tuple < SuperOfT1 > ( target.Item1 ) ; } } public interface Interface { } public class Class : Interface { } static class P...
How to work-around the limitations of the type inference in generic methods
C#
This will print something close to : ' a ( '.Is this a bug with null-coalescing operator ? If I put date ? ? `` blablabla '' in parenthesis , it is underlined as error .
DateTime ? date = null ; string tmp = `` a '' + `` ( `` + date ? ? `` blablabla '' + `` ) '' ; Console.WriteLine ( tmp ) ;
Is this a bug in Visual Studio 2010 compiler ?
C#
The code : I think the person who programmed this was `` just being careful , '' but out of interest what exceptions could be thrown on a line that does a string assignment like this one here ? I can think of System.OutOfMemoryException , but what others ? Thank you
public Constructor ( string vConnection_String ) { try { mConnection_String = vConnection_String ; } catch ( Exception ex ) { ExceptionHandler.CatchEx ( ex ) ; } }
What Exceptions Could string = string throw besides System.OutOfMemoryException ?
C#
I am trying to accurately learn the status of Tasks that are kicked off by a QueueBackgroundWorkerItem thread . I can access the Task object and add them to a List of my TaskModels , and send that list object to my View.My view only ever shows one one Task status , no matter how many times I click the QueueWorkItem lin...
List < TaskModel > taskModelList = new List < TaskModel > ( ) ; public ActionResult QueueWorkItem ( ) { Task task ; ViewBag.Message = `` State : `` ; String printPath = @ '' C : \Work\QueueBackgroundWorkerItemPractice\QueueBackgroundWorkerItemPractice\WorkerPrintFile '' + DateTime.Now.ToLongTimeString ( ) .ToString ( )...
How to store the active status of a Task , and maintain permanency of a List of these Tasks
C#
I have a simple synchronous method , looking like this : Since the method is part of a web application , it is good to use all resources as effectively as possible . Therefore , I would like to change the method into an asynchronous one . The easiest option is to do something like this : I am not an expert on either as...
public IEnumerable < Foo > MyMethod ( Source src ) { // returns a List of Oof objects from a web service var oofs = src.LoadOofsAsync ( ) .Result ; foreach ( var oof in oofs ) { // transforms an Oof object to a Foo object yield return Transform ( oof ) ; } } public async Task < IEnumerable < Foo > > MyMethodAsync ( Sou...
Various ways of asynchronously returning a collection ( with C # 7 features )
C#
It looks like in the following case the polymorphism does not work properlyI have the following definitions : Then when I call : I have `` The result is BaseInterface '' I was expecting to have `` The result is NewInterface '' as nc implement BaseClass and NewClassWhat would be the best way to get `` NewClass '' as the...
interface BaseInterface { } interface NewInterface : BaseInterface { } class NewClass : NewInterface { } class GenericClass < T > where T : BaseInterface { public string WhoIAm ( T anObject ) { return TestPolymorphism.CheckInterface ( anObject ) ; } } class ImplementedClass : GenericClass < NewInterface > { } class Tes...
Polymorphism not working for a call from a generic class in C #
C#
I 've read through a lot of really interesting stuff recently about regex . Especially about creating your own regex boundariesOne thing that I do n't think I 've seen done ( I 'm 100 % it has been done , but I have n't noticed any examples ) is how to exclude a regex match if it 's preceded by a 'special character ' ,...
( [ A-Z ] { 2 , } \\b )
How can I match two capital letters together , that are n't preceded by special characters , using regex ?
C#
I 'm using Visual Studio 2013 currently and I write this simple code : Obviously this is not a valid C # code , but the weird part is even though I see two errors , the code is compiling and working fine : I 'm thinking that migth be relevant with Roslyn because I installed Roslyn User Preview and other extensions , bu...
class Program { private static void Main ( string [ ] args ) { Console.WriteLine ( string error = `` Hello world ! `` ) ; } }
Why is my IDE complaining about new syntax after I 've installed Roslyn ?
C#
( I realize that my title is poor . If after reading the question you have an improvement in mind , please either edit it or tell me and I 'll change it . ) I have the relatively common scenario of a job table which has 1 row for some thing that needs to be done . For example , it could be a list of emails to be sent ....
ID Completed TimeCompleted anything else ... -- -- -- -- -- -- - -- -- -- -- -- -- - -- -- -- -- -- -- -- -- 1 No blabla2 No blabla3 Yes 01:04:22 ...
Is there a standard pattern for scanning a job table executing some actions ?
C#
If I call passing 0 to value : SaveOrRemove ( `` MyKey '' , 0 ) , the condition value == null is false , then CLR dont make a value == default ( T ) . What really happens ?
private static void SaveOrRemove < T > ( string key , T value ) { if ( value == null ) { Console.WriteLine ( `` Remove : `` + key ) ; } // ... }
What CLR do when compare T with null , and T is a struct ?
C#
I have to send 10000 messages . At the moment , it happens synchronously and takes up to 20 minutes to send them all.To shorten the message sending time , I 'd like to use async and await , but my concern is if C # runtime can handle 15000 number of tasks in the worker process . Also , in terms of memory , I 'm not sur...
// sending messages in a sync wayforeach ( var message in messages ) { var result = Send ( message ) ; _logger.Info ( $ '' Successfully sent { message.Title } . '' ) } var tasks = new List < Task > ( ) ; foreach ( var message in messages ) { tasks.Add ( Task.Run ( ( ) = > Send ( message ) ) } var t = Task.WhenAll ( tas...
Sending 5000 messages in async way in C #
C#
I 'm upgrading a system and am going through another developers code ( ASP.NET in C # ) .I came across this : Is checking the type on the setter unnecessary ? Surely , if I set the property to something other than a ReferralSearchFilterResults object , the code would n't even compile ? Am I missing something or am I ri...
private ReferralSearchFilterResults ReferralsMatched { get { if ( Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] == null || Session [ SESSION_REFERRAL_SEARCHFILTERRESULTS ] .GetType ( ) ! = typeof ( ReferralSearchFilterResults ) ) return null ; else return ( ReferralSearchFilterResults ) Session [ SESSION_REFERRAL_SE...
Is this redundant code ?
C#
I have a class which looks like this : The SessionReportSummaries view has a ClientId column , and I ’ m trying to join both a Client object and a ClientReportSummary object using this column.Unfortunately , NHibernate only wants to join the first one defined in the class , and always performs a SELECT for the second o...
[ Class ( Table = `` SessionReportSummaries '' , Mutable = false ) ] public class SessionReportSummaries { [ ManyToOne ( Column = `` ClientId '' , Fetch = FetchMode.Join ) ] public Client Client { get ; private set ; } [ ManyToOne ( Column = `` ClientId '' , Fetch = FetchMode.Join ) ] public ClientReportSummary ClientR...
Multiple many-to-one joins on same column erroneously results in SELECT being performed
C#
I have 4 tabs in Xamarin.Android project ( natively ) .3 tabs are loaded natively , but one tab I am loading is a Forms page ( content page ) .Here is the codes for tabs-The forms page is loaded successfully , but when I touch anywhere in that page , it crashes.Here is the exception-Updating the Xaml-When I debugged mo...
public override Android.Support.V4.App.Fragment GetItem ( int position ) { switch ( position ) { case 0 : return new tab1Fragment ( ) ; case 1 : return new tab2Fragment ( ) ; case 2 : return new tab3Fragment ( ) ; case 3 : var fragment = new FormsPage1 ( ) .CreateSupportFragment ( Android.App.Application.Context ) ; re...
Navigating native to forms in Xamarin gives null reference exception
C#
Assume I have a declared a datatable and to this datatable I have assigned a result that gets returned from calling a stored procedure , so now , my datatable contains something like the following when accessing a row from it : if firstname is changed to first_name and age is removed , the code will obviously break bec...
string name = dr [ `` firstname '' ] ; int age = ( int ) dr [ `` age '' ] ;
Is there a way to not break code if columns in a database change ?
C#
The output is `` Test '' , why is n't it null ? If s1 is passed by reference to Func ( ) , then why does myString.Append ( `` test '' ) change it , but myString = null does not ? Thanks in advance .
class Test { static void Func ( StringBuilder myString ) { myString.Append ( `` test '' ) ; myString = null ; } static void Main ( ) { StringBuilder s1 = new StringBuilder ( ) ; Func ( s1 ) ; Console.WriteLine ( s1 ) ; } }
Passing reference type in C #
C#
I have created the following classes . one base class IObject and 2 derived classes A and B.I have also created the following Service : What i want to do is get an instance of A or B but i do n't know which one i will get so i expect to get an IObject and cast it later to either A or B as shown in the example i put.Wha...
[ KnownType ( typeof ( B ) ) ] [ KnownType ( typeof ( A ) ) ] [ DataContract ( Name = `` IObject '' ) ] public class IObject { } [ DataContract ( Name= '' A '' ) ] public class A : IObject { [ DataMember ] public string s1 { get ; set ; } // Tag Name as it will be presented to the user } [ DataContract ( Name= '' B '' ...
Polymorphism WCF deserialization does n't work
C#
I ca n't seem to find an integral type that this will work on :
string foo = `` 9999999999999999999999999999999999999999999999999999999 '' ; long value ; if ( long.TryParse ( foo , out value ) ) { // do something }
Max integral type in C #
C#
After reading this question Why do `` int '' and `` sbyte '' GetHashCode functions generate different values ? I wanted to dig further and found following behavior : Difference between ( 3 ) and ( 4 ) breaks the requirement that Equals should be symmetric.Difference between ( 2 ) and ( 4 ) is not coherent with MSDN spe...
sbyte i = 1 ; int j = 1 ; object.Equals ( i , j ) //false ( 1 ) object.Equals ( j , i ) //false ( 2 ) i.Equals ( j ) //false ( 3 ) j.Equals ( i ) //true ( 4 ) i == j //true ( 5 ) j == i //true ( 6 ) i.GetHashCode ( ) == j.GetHashCode ( ) //false ( 7 )
Inconsistency in Equals and GetHashCode methods
C#
I have the following XAML : Resharper determines that FilteredPatients and SelectedPatient are ok based on the DataContext of the parent control . However , FilteredPatients is an ICollectionView and thus Resharper can not figure out that it contains instances of Patient , which has the properties specified in the Data...
< DataGrid ItemsSource= '' { Binding Path=FilteredPatients } '' SelectedItem= '' { Binding Path=SelectedPatient } '' > < DataGrid.Columns > < DataGridTextColumn Header= '' Name '' Binding= '' { Binding Path=FormattedName } '' / > < DataGridTextColumn Header= '' Date of Birth '' Binding= '' { Binding Path=BirthDate } / ...
How do I tell Resharper the type contained by an ICollectionView ?
C#
I have code similar to the following : This , of course , creates a `` Possible unintended reference comparison worked as intended '' situation . The solution to this is well documented here , and I already knew that the fix was to cast the session variable to a string as soon as I saw the code.However , the code is ye...
this.Session [ key ] = `` foo '' ; if ( ( this.Session [ key ] ? ? string.Empty ) == `` foo '' ) { //do stuff }
Possible unintended reference comparison worked as intended
C#
I have several objects inheriting from ClassA , which has an abstract method MethodA.Each of these inheriting objects can allow up to a specific number of threads simutaneously into their MethodA.The catch : Threads can only be in an object 's MethodA , while no other objects ' MethodA is being processed at the same ti...
public class ClassA { public virtual void MethodA { } } public class OneOfMySubclassesOfClassA // there can be multiple instances of each subclass ! { public override void MethodA { // WHILE any number of threads are in here , THIS MethodA shall be the ONLY MethodA in the entire program to contain threads EDIT2 : // I ...
All threads only in one method at a time ?
C#
I am trying to define an extension method that can return an object of a type defined by the call.Desired Use : Cat acat = guy.GiveMeYourPet < Cat > ( ) ; Attempted implementationI have no trouble defining generic methods like this : or extension methods like this : But when I try to do what I really want : The compile...
public static T GiveMeYourPet < T > ( Person a ) { ... } Cat acat = GiveMeYourPet < Cat > ( guy ) ; public static Cat GiveMeYourPetCat < P > ( this P self ) where P : Person , ... { ... } Cat acat = guy.GiveMeYourPetCat ( ) ; public static T GiveMeYourPet < T , P > ( this P self ) where P : Person , ... { ... } Cat aca...
How can I define a generic extension method
C#
We have a system which we use to charge the customers for different type of charges . There are multiple charge types and each charge type includes different charge items . The below is what I have come up with using the Factory Method , the problem with this one is that I need to be able to pass different parameters t...
//product abstract class public abstract class ChargeItem { public abstract List < ChargeResults > Calculate ( ) ; } //Concrete product classes public class ChargeType1 : ChargeItem { public override List < ChargeResults > Calculate ( ) { return new List < ChargeResults > { new ChargeResults { CustomerId = 1 , ChargeTo...
Design pattern / Architecture for different charge types for a customer
C#
I 'm building the unit tests for a C # MVC5 Project using Entity Framework 6 . I 'm trying to mock my BlogRepository using Moq which will then be used as an argument for the BlogController which I am attempting to test . I actually have the unit test working fine , but to do this I created a Fake BlogRepository Class ,...
Mock < IBlogRepository > blogRepo = new Mock < IBlogRepository > ( ) ; blogRepo.Setup ( t = > t.GetBlogByID ( It.IsAny < int > ( ) ) ) .Returns < Blog > ( blog = > new Blog ( ) ) ; public class BlogController : Controller { IBlogRepository blogRepo ; public BlogController ( IBlogRepository repoBlog ) { blogRepo = repoB...
How to Mock a Repository to use as an argument for a Controller ?
C#
Why does a non-closing # region causes a compiler error ? After all , the region itself has absolutely no impact on the compiled code , right ? I believe it is because it is a preprocessor directive , but why is that ? It is n't used like the other directives after all.Why ca n't it be just ignored ? Or is there a feat...
class Application { # region Whatever < - Causes an error . static void Main ( string [ ] c ) { } }
Why does # region create compiling errors ?
C#
I 'm looking for the best solution , performance wise , to rebuild a string by removing words that are not complete words . An acceptable word in this instance is a whole word without numbers or does n't start with a forward slash , or a back slash . So just letters only , but can include hyphen and apostrophe 's For e...
var resultSet = Regex.Matches ( item.ToLower ( ) , @ '' ( ? : ^|\s ) ( ? ! [ \\\/ ] ) ( ? ! -+ ( ? : \s| $ ) ) ( ? ! '+ ( ? : \s| $ ) ) ( ? ! ( ? : [ a-z'- ] * ? - ) { 3 , } ) ( ? ! ( ? : [ a-z'- ] * ? ' ) { 2 , } ) [ a-z'- ] + [ , . ] ? ( ? =\s| $ ) '' ) .Cast < Match > ( ) .Select ( m = > m.Value ) .ToArray ( ) ;
Tidy up a string
C#
Is it possible to use reflection in CompileTimeInitialize in PostSharp 3.1 ? Following code worked in 3.0 : With the 3.1 upgrade , this.locationInfo becomes Missing Property and accessing any of its properties cause NullReferenceException.Was I doing this a wrong way or has this been changed in 3.1 upgrade ? If so , ca...
public class TestClass { public string TestField ; [ TestAspect ] public void TestMethod ( ) { } } public class TestAspect : OnMethodBoundaryAspect { private LocationInfo locationInfo ; public override void CompileTimeInitialize ( MethodBase method , AspectInfo aspectInfo ) { this.locationInfo = new LocationInfo ( meth...
Can Reflection be used in CompileTimeInitialize in PostSharp 3.1 ?
C#
One of the nice things about linq was having infinite data sources processed lazily on request . I tried parallelizing my queries , and found that lazy loading was not working . For example ... This program fails to produce any results , presumably because at each step , its waiting for all calls to the generator to dr...
class Program { static void Main ( string [ ] args ) { var source = Generator ( ) ; var next = source.AsParallel ( ) .Select ( i = > ExpensiveCall ( i ) ) ; foreach ( var i in next ) { System.Console.WriteLine ( i ) ; } } public static IEnumerable < int > Generator ( ) { int i = 0 ; while ( true ) { yield return i ; i+...
How do I get lazy loading with PLINQ ?
C#
I have an ASP.NET Core 3.1 based project written using C # . I am aware that the best time to use await and async is when accessing external resources like pulling data from the database , accessing files , or making an HTTP request . This frees up the thread so more work is done instead for the thread to sit around wa...
public interface ILocator { Task < Model > ExampleAsync ( ) ; } public class Example : Controller { public ILocator Locator { get ; set ; } public Example ( ILocator locator ) { Locator = locator ; } public async Task < IActionResult > Example ( ) { Model model = await Locator.ExampleAsync ( ) ; return View ( model ) ;...
When is it not good to use await async ?
C#
The title asks it all . We use actions , expressions with actions and callbacks quite extensively in today 's code . Can the JIT optimize these calls away by inlining them ? This would be a huge performance boost , considering callback patterns , in one form or the other is used in absurd quantities today.It is not pos...
readonly Action a ; readonly Action a1 ; readonly Action a2 ; a = ( ) = > { } ; a1 = ( ) = > { a ( ) } ; a2 = ( ) = > { a1 ( ) } ;
Are deterministically unchangable Actions , and Funcs Inlined by the JIT ?