lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have in xaml : And here is screenshot ( using magnifier ) : My question is what is going on here ? Why tooltip displays value differently ( decimal point is . while , is expected ) ? Longer story : I am trying to display numbers in same format as in user Windows number format preferences.For this I 've override the l...
< TextBlock Text= '' { local : Bind Test } '' ToolTip= '' { local : Bind Test } '' / > FrameworkElement.LanguageProperty.OverrideMetadata ( typeof ( FrameworkElement ) , new FrameworkPropertyMetadata ( XmlLanguage.GetLanguage ( CultureInfo.CurrentCulture.IetfLanguageTag ) ) ) ; public class Bind : Binding { public Bind...
Tooltip culture is wrong
C#
I try to find some information about method overloading resolution in case of presence of user-defined implicit conversions and about conversions priority.This code : Produces output : So , It looks like compiler chosen user-defined conversion instead of built-in implicit conversion from int to double ( built-in conver...
class Value { private readonly int _value ; public Value ( int val ) { _value = val ; } public static implicit operator int ( Value value ) { return value._value ; } public static implicit operator Value ( int value ) { return new Value ( value ) ; } } class Program { static void ProcessValue ( double value ) { Console...
C # Method overloading resolution and user-defined implicit conversions
C#
Lets assume , we have an operation based on some file , connection , or other resource.We need a method , which can be run with provided resource , or - if not provided - creates own : } It works , but this is really ugly for me.Is it a way to write it in more compact and `` nice '' way ? I can not use : as it disposes...
string Foo ( Resource parameter = null ) { if ( parameter == null ) { using ( var res = new Resource ) { res.Something ( ) ; /* ... ... */ /* ... ... */ /* ... ... */ return /* ... ... ... .*/ } } else { parameter.Something ( ) ; /* ... ... */ /* ... ... */ /* ... ... */ return /* ... ... ... .*/ } } string Foo ( Resou...
C # conditional using and default parameter
C#
I need a PHP version of the following C # code : ... this code snippet appears to be incomplete . But here 's what I think is going on : concatenating dateSince , siteID , and sharedSecret . Stealing underpants. ? ? ? converting that string into a ascii encoded byte array.taking the MD5 hash of that array.This mysterio...
string dateSince = `` 2010-02-01 '' ; string siteID = `` bash.org '' ; string sharedSecret = `` 12345 '' ; // the same combination on my luggage ! using System.Security.Cryptography ; MD5CryptoServiceProvider x = new MD5CryptoServiceProvider ( ) ; byte [ ] dataBytes = System.Text.Encoding.ASCII.GetBytes ( string.Format...
How would I translate this C # code into PHP ?
C#
I have a Linq query with a select , from my Linq query provider it I get an expression tree containing a MethodCallExpression , but just how can I get the select projections from the MethodCallExpression ? Query may look like :
internal static object Execute ( Expression expression , bool isEnumerable ) { var whereExpression = expression as MethodCallExpression ; if ( whereExpression == null ) throw new InvalidProgramException ( `` Error '' ) ; foreach ( var arg in whereExpression.Arguments ) { if ( arg is UnaryExpression ) { var unaryExpress...
Getting projections from MethodCallExpression
C#
I am creating a console application for the purpose of learning the state and observer patterns . The program is based on a basic order system whereby each order can have a state ( pending , ready , submitted i.e state pattern ) and subscribers that are interested in receiving notifications from the order when it gets ...
public class Order : IOrder , IOrderState , IObservable public interface IOrder : IOrderState , IObservable
Should these interfaces be inherited at interface level or implemented at class level ?
C#
Imagine this C # code in some method : Let 's say no one is using any explicit memory barriers or locking to access the dictionary . If no optimization takes place , then the global dictionary should be either null ( initial value ) or a properly constructed dictionary with one entry.The question is : Can the effect of...
SomeClass.SomeGlobalStaticDictionary = new Dictionary < int , string > ( ) { { 0 , `` value '' } , } ;
Can another thread see partially created collection when using collection initializer ?
C#
So I made myself a C # -WebApi REST Service.When I build/run my application in Visual Studio everything works perfectly.But everytime I try to publish my project as a filesystem , two errors appear in the error list . The strange thing here is that these errors disappear after a few seconds and no errors are shown.Erro...
public override void CopyProperties ( object other ) { base.CopyProperties ( other ) ; Contracts.IEvent _event = other as Contracts.IEvent ; if ( _event ! = null ) { this.Description = _event.Description ; this.Enddate = _event.Enddate ; this.Host = _event.Host ; this.Location = _event.Location ; this.Name = _event.Nam...
Visual Studio 2013 publishing fails and reports `` non-existing '' error
C#
please look at the below code : and the result is : FalseTrueand now consider this one : and the result is : TrueTrue “ == ” compares if the object references are same while “ .Equals ( ) ” compares if the contents are same . and i want to know what is different between these codes ? ! and both of them turn out an obje...
using System ; class MyClass { static void Main ( ) { object o = `` .NET Framework '' ; object o1 = new string ( `` .NET Framework '' .ToCharArray ( ) ) ; Console.WriteLine ( o == o1 ) ; Console.WriteLine ( o.Equals ( o1 ) ) ; } } using System ; class MyClass { static void Main ( ) { object o = `` .NET Framework '' ; o...
`` stringDemo '' versus new string ( `` stringDemo '' .ToCharArray ) ;
C#
2nd edit : I think my original test script has an issue , the 10000000 times loop is , in fact , dealing with the same memory location of an array , which makes the unsafe version ( provided by Marc here ) much faster than bitwise version . I wrote another test script , I noticed that bitwise and unsafe offers almost t...
unsafe class UnsafeRaw { public static short ToInt16BigEndian ( byte* buf ) { return ( short ) ToUInt16BigEndian ( buf ) ; } public static int ToInt32BigEndian ( byte* buf ) { return ( int ) ToUInt32BigEndian ( buf ) ; } public static long ToInt64BigEndian ( byte* buf ) { return ( long ) ToUInt64BigEndian ( buf ) ; } p...
C # Signed & Unsigned Integral to Big Endian Byte Array , and vice versa using Bitwise way with `` best '' performance
C#
I have a .NET Console App integrated with Entity Framework and Discord Sharp Plus with the following libraries : DSharpPlusDSharpPlus.CommandsNextMicrosoft.EntityFrameworkCore.DesignMicrosoft.EntityFrameworkCore.SqliteMicrosoft.EntityFrameworkCore.ToolsRunning the application without debugging ( Control + F5 in Visual ...
Database.Commands.SingleOrDefault ( x = > x.CommandTrigger == name ) private readonly string dbPath = $ '' Data Source= { Environment.GetEnvironmentVariable ( `` YuutaDbPath '' ) } '' ; public DbSet < Guild > Guilds { get ; set ; } // ... // ... protected override void OnConfiguring ( DbContextOptionsBuilder options ) ...
.NET Console App with Entity Framework Core : 'The process has no package identity ' only when started without debugging
C#
On my ASPX page I 've added Dropdownlist.Elements in this list are divided to groups by adding disabled list items : Those list items are grayed , I ca n't select it by mouse or by clicking cursor arrows ( up/down ) .That is correct.But problem is , that after clicking '- ' key this list item is selected . I think that...
ListItem separator = new ListItem ( `` -- -My friends -- - '' , `` '' ) ; separator.Attributes.Add ( `` disabled '' , `` true '' ) ; _ddUsersList.Items.Add ( separator ) ;
Error in Dropdownlist
C#
I 've written two LINQ queries using the join method . Essentially , if I switch the order of the objects to be joined , the query no longer works and throws the error : '' Unable to create a constant value of type 'Domain.Entities.UsersSitesRole ' . Only primitive types ( 'such as Int32 , String , and Guid ' ) are sup...
var foo2 = //works from p in privilegesForUser join c in repository.Child on p.SiteId equals c.Child_SiteID select new { ChildID = c.Child_ChildID , name = c.Child_FirstName , site = c.Child_SiteID , p.PrivilegeLevel } ; var foo3 = //throws exception from c in repository.Child join p in privilegesForUser on c.Child_Sit...
Why does this LINQ join query work , but this other one does n't ?
C#
I have the following code : This is a modified example from CLR via C # 4th ed ( pg 138 ) .In the book it says thatwill output `` ( 2 , 2 ) '' because the boxed p will be immediately garbage collected.However , would n't the actual reason for this be the fact that changing the value of a boxed variable only changes the...
//Interface defining a Change methodinternal interface IChangeBoxedPoint { void Change ( Int32 x , Int32 y ) ; } internal struct Point : IChangeBoxedPoint { private Int32 m_x , m_y ; public Point ( Int32 x , Int32 y ) { m_x = x ; m_y = y ; } public void Change ( Int32 x , Int32 y ) { m_x = x ; m_y = y ; } public overri...
Changing a struct after boxing it
C#
I am trying to read foreign characters from an .ini file.This is the method I am usingI am using Encoding.ASCII but apparently GetPrivateProfileString is n't . The bytes coming out of it need encoding probably . How can I do that ? Edit : ExampleThis will print : Tavar ? instead of Tavaré
[ DllImport ( `` kernel32 '' ) ] public static extern int GetPrivateProfileString ( string Section , int Key , string Value , [ MarshalAs ( UnmanagedType.LPArray ) ] byte [ ] Result , int Size , string FileName ) ; public static string [ ] GetEntryNames ( string section , string iniPath ) { for ( int maxsize = 500 ; tr...
File read foreign characters
C#
Are there any C # specifications that state how implicit conversions of terms of integral types ( e.g. , int ) to terms of double are supposed to work ? If so , can someone tell me the algorithm or direct me to it ? C # 6.0 draft specification states “ the value of a real literal of type float or double is determined b...
using System ; using System.Diagnostics ; namespace App { internal static class Program { internal static void Main ( ) { Debug.Assert ( GetFirstByte ( 10648738977740919977 ) ! = GetFirstByte ( 10648738977740919977d ) ) ; } private static byte GetFirstByte ( double val ) { return BitConverter.GetBytes ( val ) [ 0 ] ; }...
How does C # implicitly cast terms of integral types to terms of double ?
C#
My class has a method which produces a Task < int > object using a TaskCompletionSource < int > . Then it does some asynchronous operations and sets the result . I need to know whether I can trust the task 's ContinueWith method or not : Can the caller of CalculateAsync method do something with the produced task and pr...
public Task < int > CalculateAsync ( ) { var source = new TaskCompletionSource ( ) ; DoSomeAsyncStuffAndSetResultOf ( source ) ; source.Task.ContinueWith ( t = > Console.WriteLine ( `` Is this reliable ? `` ) ) ; return source.Task ; }
How to cancel a task 's continuation ?
C#
I am currently cleaning up some of our legacy code base in which we make use of extern methods . The parameter names are all over the place in terms of naming conventions . I 'd like to consolidate them.ExampleCan I safely rename new_status to newStatus or will that break the contract ? ReSharper suggests it as a chang...
[ DllImport ( `` customdll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void SetStatus ( int new_status ) ;
Is it safe to rename extern method parameters in C # ?
C#
Does there exist a standard pattern for yield returning all the items within an Enumerable ? More often than I like I find some of my code reflecting the following pattern : The explicit usage of a foreach loop solely to return the results of an Enumerable reeks of code smell to me . Obviously I could abandon the use o...
public IEnumerable < object > YieldReturningFunction ( ) { ... [ logic and various standard yield return ] ... foreach ( object obj in methodReturningEnumerable ( x , y , z ) ) { yield return obj ; } }
What is the proper pattern for handling Enumerable objects with a yield return ?
C#
I want to know is there a better/easier way to load users by birthday.I have a User instance , which has properties , including this one : public DateTime ? BirthDate { get ; set ; } What I want to do is to load that users who has bdays from one date to another : I do n't care about birthday year , for example , if I h...
public IEnumerable < User > LoadUsersByBirthday ( DateTime from , DateTime into ) public IEnumerable < User > LoadUsersByBirthday ( DateTime from , DateTime into ) { var days = DateTime.DaysInMonth ( from.Year , from.Month ) ; var u1 = _unit.User.Load ( u = > ( ( DateTime ) ( u.BirthDate ) ) .Month == from.Month & & ( ...
Load users by birthday
C#
I 'm experimenting with switch statement pattern matching , and I 'm looking for a way to return false if either value in a two value tuple is zero . This is the code I 'm trying : In VSCode 1.47 and dotnetcore 3.14 I get a compile-time error : CS8652 : The feature 'type pattern ' is in Preview ` What is the best compa...
static bool IsAnyValueZero ( ( decimal , decimal ) aTuple ) { switch ( aTuple ) { case ( decimal , decimal ) t when t.Item1 == 0 || t.Item2 == 0 : return true ; } return false ; }
How to use C # pattern matching with tuples
C#
I was wondering how could I use a custom object in more than one panel.I made a panelModified object ( extends from Panel ) and want to place it in two normal panels , so when the object change its status , both panels display the updated information.In my case the `` panelModified '' is a panel with some Buttons and a...
panelPreview = new PanelPreview ( file ) ; ( panelModified object ) panel1.Controls.Add ( panelPreview ) ; panel2.Controls.Add ( panelPreview ) ;
How can I show an object in multiple panels ?
C#
I have a class of this type : But sometimes I need to use this class as a non generic class , ie the type TResult is void.I ca n't instantiate the class in the following way : Also , I 'd rather not specify the type omitting the angle brackets : I do n't want re-write the whole class because it does the same thing .
class A < TResult > { public TResult foo ( ) ; } var a = new A < void > ( ) ; var a = new A ( ) ;
What if T is void in Generics ? How to omit angle brackets
C#
I stumbled across this article and found it very interesting , so I ran some tests on my own : Test One : Outputs : Test Two : Outputs : According to the article , in Test One all of the lambdas contain a reference to i which causes them to all output 5 . Does that mean I get the expected results in Test Two because a ...
List < Action > actions = new List < Action > ( ) ; for ( int i = 0 ; i < 5 ; ++i ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; foreach ( Action action in actions ) action ( ) ; 55555 List < Action > actions = new List < Action > ( ) ; for ( int i = 0 ; i < 5 ; ++i ) { int j = i ; actions.Add ( ( ) = > Console.Wr...
odd lambda behavior
C#
I 'm trying to connect Chrome extension and my C # application.I 'm using this code https : //stackoverflow.com/a/13953481/3828636Everything is almost working there in only one problem I can send message only 6 times and than my c # app does n't recieve anything . When I re-open my extension ( click on icon ) it works ...
function send ( data ) { var data = new FormData ( ) ; var xhr = new XMLHttpRequest ( ) ; xhr.open ( 'POST ' , listener , true ) ; xhr.onload = function ( ) { } ; xhr.send ( data ) ; }
Communication JQuery and C #
C#
Executing a UWP application in DEBUG works perfectly.Using exactly the same code compiled in RELEASE crashes with this error message when executing this code ( it 's using Dapper 1.5.1 and System.Data.SQLite 1.0.109.2 ) The application is UWP configured as below . Furthermore , the faulting code is a .NET Standard 2.0 ...
System.PlatformNotSupportedException : 'Dynamic code generation is not supported on this platform . ' using ( var c = NewConnection ( ) ) { var sql = @ '' update settings set `` '' value '' '' = @ SetDate where `` '' key '' '' = 'week_date ' '' ; c.Execute ( sql , new { SetDate = date } ) ; // < = throws PlatformNotSup...
PlatformNotSupportedException throws when using Dapper with WP
C#
I 'm trying to debug ( hit breakpoint ) a python script which is executed through a new process from C # .I have installed Child Process Debugging Power tool as that tool supposedly allows one to do that.According to its documentation it requires two things : The parent process must be debugged with the native debuggin...
ProcessStartInfo startInfo = new ProcessStartInfo ( ) ; Process p = new Process ( ) ; startInfo.CreateNoWindow = true ; startInfo.UseShellExecute = false ; startInfo.RedirectStandardOutput = false ; startInfo.RedirectStandardError = true ; startInfo.RedirectStandardInput = false ; ... p.StartInfo = startInfo ; p.Enable...
Mixed mode Debugging Python/C # using Child Process Debugging Power Tool
C#
** I have 36 of these case statements each one for another for a different picture box ; how do I group them all into one case statement so my code can be more efficient**
private void makeMoleVisable ( int mole , PictureBox MoleHill ) { switch ( mole ) { case 1 : if ( p01.Image == pmiss.Image & & MoleHill.Image == pHill.Image ) { molesmissed ++ ; } p01.Image = MoleHill.Image ; break ; case 2 : if ( p02.Image == pmiss.Image & & MoleHill.Image == pHill.Image ) { molesmissed++ ; } p02.Imag...
How do I merge all the cases into One ?
C#
The following code works if Cassandra and the code are on the same machine : Assuming a username and password is needed if the code is on one machine and cassandra is on a different machine ( different ip address ) ? So I have tried : I get the following error message : The iptables on the node ( the cassandra server )...
using System ; using Cassandra ; namespace CassandraInsertTest { class Program { static void Main ( string [ ] args ) { var cluster = Cluster.Builder ( ) .AddContactPoint ( `` 127.0.0.1 '' ) .Build ( ) ; var session = cluster.Connect ( `` test_keyspace '' ) ; session.Execute ( `` INSERT INTO test_table ( id , col1 , co...
How do I connect to a Cassandra VM
C#
I have set up a VirtualPathProvider and it is working fine for direct url calls like http : // ... /home/index in the address bar.However , I would like this to work for the Html helper too , but right now it is ignoring the VirtualPathProvider for the html helper calls in the view : Is there a way to solve this proble...
public class HomeController { public ActionResult Index ( ) { // This triggers MyVirtualPathProvider functionallity when called via // the browsers address bar or anchor tag click for that matter . // But it does not trigger MyVirtualPathProvider for 'in-view ' calls like // @ { Html.RenderAction ( `` index '' , `` hom...
Html helper does not use custom VirtualPathProvider
C#
This is a followup to this question : Cast < int > .Cast < int ? > applied on generic enum collection results in invalid cast exceptionWhy is that Gender [ ] is IEnumerable < int > returns true in the generic case ? Especially when they are not type compatible ? It had tripped me in the question I linked ! I think this...
enum Gender { Male , Female } Gender g = Gender.Male ; bool b = g is int ; // false , alright no issuesb = new [ ] { g } is IEnumerable < int > ; // false , alright no issuesb = Is < Gender , int > ( g ) ; //false , alright no issuesb = Is < Gender [ ] , IEnumerable < int > > ( new [ ] { g } ) ; // true , why on earth ...
enum [ ] is IEnumerable < int > returns true in a generic method
C#
I think my logic is flawed ... .in a loop I have : this loop updates approximately once per second ... .the problem I have is that seconds always ends up with a zero ( 0 ) value . this is because the ItemPos value is always higher after first loop than elapsed.TotalSeconds . So for example : if 3 seconds passWhat am I ...
int seconds = ( int ) ( elapsed.TotalSeconds / ItemPos ) * ( Count - ItemPos ) ; ItemCount = 20 , so 3/20 = 0.15 - rounds to zero ... . 0 * anything = 0 ... ...
Estimated time remaining , what am I missing ?
C#
I was working through the MSDN tutorial for Crystal Reports , and I get to the Binding the Embedded Report to the CrystalReportViewer Control step : When I try the build , it tells me that I am missing my using declaration for Hierarchical_Grouping class . This brings up two questions for me ... What is the namespace f...
using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Text ; using System.Windows.Forms ; using CrystalDecisions.CrystalReports.Engine ; using CrystalDecisions.Shared ; namespace CrystalTest3 { public partial class Form1 : Form { private ...
Missing Using directive for hierarchical_grouping in MSDN crystal reports tutorial
C#
Run enumeration of IAsyncEnumerable twice not possible ? Once CountAsync has been run , the await foreach wo n't enumerate any item . Why ? It seems there is no Reset method on the AsyncEnumerator.Source of data
var count = await itemsToImport.CountAsync ( ) ; await foreach ( var importEntity in itemsToImport ) { // wo n't run } private IAsyncEnumerable < TEntity > InternalImportFromStream ( TextReader reader ) { var csvReader = new CsvReader ( reader , Config ) ; return csvReader.GetRecordsAsync < TEntity > ( ) ; }
Run enumeration of IAsyncEnumerable twice not possible ?
C#
My answer to one of the question on SO was commented by Valentin Kuzub , who argues that inlining a property by JIT compiler will cause the reflection to stop working . The case is as follows : Fuzz function accepts a lambda expression and uses reflection to find the property . It is a common practice in MVC in HtmlHel...
class Foo { public string Bar { get ; set ; } public void Fuzz < T > ( Expression < Func < T > > lambda ) { } } Fuzz ( x = > x.Bar ) ;
Property / Method inlining and impact on Reflection
C#
I have a 123MB big intarray , and it is basically used like this : eval ( ) is called a lot ( ~50B times ) with different c and I would like to know if ( and how ) I could speed it up . I already use a unsafe function with an fixed array that makes use of all the CPUs . It 's a C # port of the TwoPlusTwo 7 card evaluat...
private static int [ ] data = new int [ 32487834 ] ; static int eval ( int [ ] c ) { int p = data [ c [ 0 ] ] ; p = data [ p + c [ 1 ] ] ; p = data [ p + c [ 2 ] ] ; p = data [ p + c [ 3 ] ] ; p = data [ p + c [ 4 ] ] ; p = data [ p + c [ 5 ] ] ; return data [ p + c [ 6 ] ] ; }
Speeding up array lookup after traversing ?
C#
I 've found very strange C # compiler behavior for following code : In last line assert fails with following message : I understand why test fails : p2 = new SqlParameter ( `` @ p '' , 0 ) ; is resolved as SqlParameter ( string , SqlDbType ) and for other cases as SqlParameter ( string , object ) . But I do n't underst...
var p1 = new SqlParameter ( `` @ p '' , Convert.ToInt32 ( 1 ) ) ; var p2 = new SqlParameter ( `` @ p '' , 1 ) ; Assert.AreEqual ( p1.Value , p2.Value ) ; // PASS var x = 0 ; p1 = new SqlParameter ( `` @ p '' , Convert.ToInt32 ( x ) ) ; p2 = new SqlParameter ( `` @ p '' , x ) ; Assert.AreEqual ( p1.Value , p2.Value ) ; ...
Strange C # compiler behavior ( overload resolution )
C#
I have a few jobs executed one after the other via ContinueJobWith < MyHandler > ( parentJobId , x = > x.DoWork ( ) ) .However , the second job is not getting processed and always sits in Awaiting state : The job itself is like this : Why this can happen and where to check for resultion ? We are using Autofac as DI con...
builder.RegisterType < BackgroundJobStateChanger > ( ) .As < IBackgroundJobStateChanger > ( ) .InstancePerLifetimeScope ( ) ; var parentJobId = _backgroundJobClient.Schedule < Handler > ( h = > h.ConvertCertToTraining ( certId , command.SetUpOneToOneRelationship ) , TimeSpan.FromSeconds ( 1 ) ) ; var filesCopyJObId = _...
Hangfire ContinueWithJob is stuck in awaiting state , though parent job has succeeded
C#
Is it possible somehow to define a constant that says what datatype to use for certain variables , similar to generics ? So in a certain class I would have something like the following : From the principle it should do the same as generics but I do n't want to write the datatype every time the constructor for this clas...
MYTYPE = System.String ; // some other code hereMYTYPE myVariable = `` Hello '' ;
C # : Declaring a constant variable for datatype to use
C#
I made an winform application that can detect , set and toggle IPv4 settings using C # . When the user wants to get IP automatically from DHCP I call Automatic_IP ( ) : Automatic_IP : And in the Getip method I extract the current IP address , subnet , gateway and the DNS regardless of the fact that all these could be m...
private void Automatic_IP ( ) { ManagementClass mctemp = new ManagementClass ( `` Win32_NetworkAdapterConfiguration '' ) ; ManagementObjectCollection moctemp = mctemp.GetInstances ( ) ; foreach ( ManagementObject motemp in moctemp ) { if ( motemp [ `` Caption '' ] .Equals ( _wifi ) ) //_wifi is the target chipset { mot...
Detecting if `` Obtain IP address automatically '' is selected in windows settings
C#
I 'm developing a game using XNA and C # and was attempting to avoid calling new struct ( ) type code each frame as I thought it would freak the GC out . `` But wait , '' I said to myself , `` struct is a value type . The GC should n't get called then , right ? '' Well , that 's why I 'm asking here.I only have a very ...
spriteBatch.Draw ( tex , new Rectangle ( x , y , width , height ) , Color.White ) ;
What happens when value types are created ?
C#
I saw the following code , Based on my understanding , I think the code should be rewritten as follows : Is that correct ? Based on http : //msdn.microsoft.com/en-us/library/scekt9xw % 28v=vs.80 % 29.aspxAn is expression evaluates to true if the provided expression is non-null , and the provided object can be cast to t...
public override bool Equals ( object obj ) { // From the book http : //www.amazon.co.uk/Pro-2010-NET-4-0-Platform/dp/1430225491 // Page 254 ! if ( obj is Person & & obj ! = null ) ... } public override bool Equals ( object obj ) { if ( obj is Person ) ... } using System ; using System.Collections.Generic ; using System...
C # -- Is this checking necessary `` obj is Person & & obj ! = null ''
C#
I have two similar queries theoretically returning the same results : This request returns 0 items , even though it is supposed to return one.The following is a rewrite of the latter but with a call to the ToList ( ) method . This request works and returns the item expected in the first query ! Note : SessionManagement...
var requestNotWorking = SessionManagement.Db.Linq < Item > ( false ) .Where ( i = > i.Group ! = null & & i.Group.Id == methodParameter ) .ToList ( ) ; var requestWorking = SessionManagement.Db.Linq < Item > ( false ) .ToList ( ) .Where ( i = > i.Group ! = null & & i.Group.Id == methodParameter ) .ToList ( ) ;
Unexpected Linq Behavior - ToList ( )
C#
I am using HTML Agility pack in Xamarin forms to scrape data from a website . When a condition returns true , I want to send a push notification to all users . However , this data is changing a lot and I think it would cost a lot of internet data and maybe battery , if the device with this app is constantly collecting ...
var url = `` https : //www.goal.com/en-us/live-scores '' ; var httpClient = new HttpClient ( ) ; var html = await httpClient.GetStringAsync ( url ) ; var htmlDocument = new HtmlDocument ( ) ; htmlDocument.LoadHtml ( html ) ; var voetbalWedstrijdenHTML = htmlDocument.DocumentNode.Descendants ( `` div '' ) .Where ( node ...
Use code on one device and show 'result ' with others using push notifications
C#
Can I write a hash code function for the following comparer logic ? Two instances of My are equal if at least two properites from ( A , B , C ) match.The Equals part is simple , but I 'm stumped on the hash code part , and part of me is thinking it might not be possible.UPDATE : In addition to the correct answer by Ree...
class MyOtherComparer : IEqualityComparer < My > { public bool Equals ( My x , My y ) { if ( Object.ReferenceEquals ( x , y ) ) return true ; if ( Object.ReferenceEquals ( x , null ) || Object.ReferenceEquals ( y , null ) ) return false ; int matches = 0 ; if ( x.A == y.A ) matches++ ; if ( x.B == y.B ) matches++ ; if ...
Is it possible to write a hash code function for an comparer that matches many-to-many ?
C#
The .NET reference source shows the implementation of NextBytes ( ) as : InternalSample provides a value in [ 0 , int.MaxValue ) , as evidenced by it 's doc comment and the fact that Next ( ) , which is documented to return this range , simply calls InternalSample . My concern is that , since InternalSample can produce...
for ( int i=0 ; i < buffer.Length ; i++ ) { buffer [ i ] = ( byte ) ( InternalSample ( ) % ( Byte.MaxValue+1 ) ) ; }
Is Random.NextBytes biased ?
C#
I 'm currently writing a CLR profiler , and I came across something very odd . When throwing two different exceptions , one from the try clause and one from the catch clause , the CLR notifies me of the same instruction pointer.More specifically : I 'm registered to receive the ExceptionThrown callbackvirtual HRESULT S...
try { try { throw new Exception ( `` A '' ) ; } catch ( Exception ) { StackTrace st = new StackTrace ( true ) ; StackFrame sf = st.GetFrame ( 0 ) ; Console.WriteLine ( `` Inside catch , instruction : `` + sf.GetILOffset ( ) + `` . line : `` + sf.GetFileLineNumber ( ) ) ; throw new Exception ( `` B '' ) ; } } catch ( Ex...
CLR Profiling : DoStackSnapshot after a throw inside a catch block gives wrong instruction pointer
C#
I 'm building a message dispatch map in C # and mostly just playing around with some different approaches . I am curious about a performance difference I am measuring , but it 's not obvious why from looking at the IL.The message map : I then have a class hierarchy of Messages , similar to EventArgs in WPF , for exampl...
delegate void MessageHandler ( Message message ) ; AddHandler ( Type t , MessageHandler handler ) { /* add 'handler ' to messageMap invocation list */ } delegate void GenericMessageHandler < T > ( T message ) ; AddHandler < T > ( GenericMessageHandler < T > handler ) where T : Message { AddHandler ( typeof ( T ) , e = ...
Why is casting to a generic type slower than an explicit cast in C # ?
C#
I am trying to derive a class from ObservableCollection and I need to run just a single line of code each and every time any instance of this class is deserialized . My thought was to do this : But I do n't have access to those base methods related to serialization . Am I forced to re-write all of the serialization man...
[ Serializable ] public class ObservableCollection2 < T > : ObservableCollection < T > , ISerializable { public ObservableCollection2 ( ) : base ( ) { } public ObservableCollection2 ( SerializationInfo info , StreamingContext context ) : base ( info , context ) { // Put additional code here . } void ISerializable.GetOb...
How can I run code in a C # class definition each time any instance of the class is deserialized ?
C#
In MVC3 , we could use the CanvasAuthorize Attribute ( in old FaceBook version ) properties like LoginDisplayMode , ReturnUrlPath , CancelUrlPath.How can we use them in Latest version 6.4 ? We have [ FacebookAuthorize ( `` Permissions '' ) ] in the MVC4 . But , how we could use other properties like LoginDisplayMode , ...
[ CanvasAuthorize ( Permissions = `` '' , LoginDisplayMode = `` popup '' , ReturnUrlPath = `` Some Url '' , CancelUrlPath = `` Some Url '' ) ] public ActionResult Index ( ) { return View ( ) ; }
What is the substitute of CanvasAuthorizeAttribute in FaceBook C # SDK 6.4 version
C#
Assume I have a classNow I want to filter duplicates in list of such audio 's by similarity ( not EXACT match ) condition . Basicaly it 's Levenstein distance with treshold correction by string total length . The problem is , general tip about IEqualityComparer is `` Always implement both GetHashCode and Compare '' . I...
public class Audio { public string artist { get ; set ; } public string title { get ; set ; } // etc . }
.net Distinct ( ) and complex conditons
C#
I want my View to be as follows : This leads me to believe I need a Model that contains a list of another Model . So in a project containing nothing but this I would have : Is this correct or is there a better way ?
@ model MyProgram.Models.DocumentList @ { ViewBag.Title = `` View1 '' ; } @ foreach ( MyProgram.Models.Document doc in Model.GetDocs ( ) ) { < p > doc.Content < /p > } /Model/DocumentList.cs/Model/Document.cs
Simple best practices for ASP.NET models
C#
I understand that .NET is multi-threaded and that is a good thing , but I continually run into issues when I have a background worker for example that is updating some control on my form and I have to do : My question is why is this not built into the framework - surely if I am trying to update a DataGridView it should...
Private Sub SetRowCellBoolValueThreadSafe ( ByVal row As Integer , ByVal col As Integer , ByVal value As Boolean ) If dgvDatabase.InvokeRequired Then Dim d As New SetRowCellBoolValueCallback ( AddressOf SetRowCellBoolValue ) Me.Invoke ( d , New Object ( ) { row , col , value } ) Else SetRowCellBoolValue ( row , col , v...
Why is n't Invoke via Delegate built into .NET
C#
I have a LinqToEntities query that double produces a subquery when creating the SQL . This causes the result set to come back with 0-3 results , every time the query is run . The subquery on its own produces a single random result ( as it should ) . What is going on here ? The LINQ query : Produce this SQL : EDIT : So ...
from jpj in JobProviderJobswhere jpj.JobID == 4725 & & jpj.JobProviderID == ( from jp2 in JobProviderJobs where jp2.JobID == 4725 orderby Guid.NewGuid ( ) select jp2.JobProviderID ) .FirstOrDefault ( ) select new { JobProviderID = jpj.JobProviderID } SELECT [ Filter2 ] . [ JobID ] AS [ JobID ] , [ Filter2 ] . [ JobProv...
LinqToEntities produces incorrect SQL ( Doubled Subquery )
C#
If I include outside reference inside where predicate then memory does not get releases.Let 's say I have a List < object > then if I write a where predicate like this : Even If I make myList = null or predicate = null , it is not releasing memory . I have List < object > itemsource binded to DataGrid . I also make it ...
List < object > myList = new List < object > ( ) ; ... myList.add ( object ) ; ... Expression < Func < object , bool > > predicate = p = > myList.Contains ( p ) ; Expression < Func < object , bool > > predicate = p = > p.id == 0 ;
Where predicates does not releases memory
C#
I built an application that can also be ran as a service ( using a -service ) switch . This works perfectly with no issues when I 'm running the service from a command prompt ( I have something set up that lets me debug it from a console when not being ran as a true service ) . However , when I try to run it as a true ...
[ STAThread ] static void Main ( string [ ] args ) { //Convert all arguments to lower args = Array.ConvertAll ( args , e = > e.ToLower ( ) ) ; //Create the container object for the settings to be stored Settings.Bag = new SettingsBag ( ) ; //Check if we want to run this as a service bool runAsService = args.Contains ( ...
Using memory maps with a service
C#
I have many working Entity Framework Scalar Function 's . However , when I try to return a 'truthy ' value through a scalar function I get the following exception : The specified method 'Boolean svfn_CanCloneDocument ( Int32 , System.String ) ' on the type 'ETC.Operations.DbClient.DbClient.Data.DbClientContext ' can no...
public IQueryable < ShakeoutDataItem > Query ( ) { var uow = UnitOfWork as DbClientUnitOfWork ; var dbContext = UnitOfWork.DbContext as DbClientContext ; var query = ( from document in dbContext.vDocumentStatus join shakeout in uow.Shakeout on document.DocumentId equals shakeout.DocumentId join shakeoutDetail in uow.Sh...
Bit-Bool on a Entity Framework Scalar Function Throws ' can not be translated ' Exception
C#
Let 's have two code snippets : A : B : In case A the CLR will not even call the Bar ctor ( unless it is debug build or the debugger is attached ) , however in case B it is called under all circumstances.The thing is that in Bar constructor one can have calls that will make this instance reachable from elsewhere - most...
public class Foo { private static Bar _unused = new Bar ( ) ; } public class Foo { private static Bar _unused ; static Foo ( ) { _unused = new Bar ( ) ; } }
Why CLR optimizing away unused static field with initialization ?
C#
So I have been playing around with C # lately and I do n't understand output formatting.OutputMy expected output was index i holds number Number [ i ] . So can anyone explain what to change , or link me with a good C # page on output formatting topic.I know there is a way to do it in 2 lines .
using System ; namespace Arrays { class Program { static void Main ( ) { Random r = new Random ( ) ; int [ ] Numbers = new int [ 10 ] ; for ( int i = 0 ; i < Numbers.Length ; i++ ) { Numbers [ i ] = r.Next ( 101 ) ; } for ( int i = 0 ; i < Numbers.Length ; i++ ) { Console.WriteLine ( `` index { 0 } holds number { 0 } '...
Simple C # output
C#
I 've been playing around with optional parameters and came accross the following scenario.If I have a method on my class where all the parameters are optional I can write the following code : If I then create an interface such as : If I make the Test class implement this interface then it wo n't compile as it says int...
public class Test { public int A ( int foo = 7 , int bar = 6 ) { return foo*bar ; } } public class TestRunner { public void B ( ) { Test test = new Test ( ) ; Console.WriteLine ( test.A ( ) ) ; // this recognises I can call A ( ) with no parameters } } public interface IAInterface { int A ( ) ; }
When interface method has no parameters why is n't the implementation recognised of a method with all optional parameters ?
C#
I am trying to implement a caching mechanism for enumerating collections safely , and I am checking if all modifications of the built-in collections are triggering an InvalidOperationException to be thrown by their respective enumerators . I noticed that in the .NET Core platform the Dictionary.Remove and Dictionary.Cl...
var dictionary = new Dictionary < int , string > ( ) ; dictionary.Add ( 1 , `` Hello '' ) ; dictionary.Add ( 2 , `` World '' ) ; foreach ( var entry in dictionary ) { var removed = dictionary.Remove ( entry.Key ) ; Console.WriteLine ( $ '' { entry } removed : { removed } '' ) ; } Console.WriteLine ( $ '' Count : { dict...
Dictionary methods Remove and Clear ( .NET Core ) modify the collection during enumeration . No exception thrown
C#
I am writing a simple Memoize helper that allows caching method results instead of computing them every time . However , when I try to pass a method into Memoize , the compiler ca n't determine the type arguments . Are n't they obvious from my method signature ? Is there a way around this ? Sample code : Error message ...
using System ; using System.Collections.Concurrent ; public static class Program { public static Func < T , V > Memoize < T , V > ( Func < T , V > f ) { var cache = new ConcurrentDictionary < T , V > ( ) ; return a = > cache.GetOrAdd ( a , f ) ; } // This is the method I wish to memoize public static int DoIt ( string ...
Why do I have to explicitly specify my type arguments for Func parameters ?
C#
Running an empty for-loop with large numbers of iterations , I 'm getting wildly different numbers in how long it takes to run : The above will run in around 200ms on my machine , but if I increase it to 1000000001 , then it takes 4x as long ! Then if I make it 1000000002 , then it 's down to 200ms again ! This seems t...
public static class Program { static void Main ( ) { var sw = new Stopwatch ( ) ; sw.Start ( ) ; for ( var i = 0 ; i < 1000000000 ; ++i ) { } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedMilliseconds ) ; } } public static class Program { static void Main ( ) { var sw = new Stopwatch ( ) ; sw.Start ( ) ; object o = null ...
for-loop performance oddity in .NET x64 : even-number-iteration affinity ?
C#
I am trying to enumerate a large IEnumerable once , and observe the enumeration with various operators attached ( Count , Sum , Average etc ) . The obvious way is to transform it to an IObservable with the method ToObservable , and then subscribe an observer to it . I noticed that this is much slower than other methods...
using System ; using System.Diagnostics ; using System.Linq ; using System.Reactive.Disposables ; using System.Reactive.Linq ; using System.Reactive.Subjects ; using System.Reactive.Threading.Tasks ; public static class Program { static void Main ( string [ ] args ) { const int COUNT = 10_000_000 ; Method1 ( COUNT ) ; ...
Why is IEnumerable.ToObservable so slow ?
C#
I have : How I make it , as MyBook to inherit the top-level Book namespace , instead of Company 's ?
namespace Book { ... } ... ... namespace Company { public class Book { } ... ... ... ... ... ... public class MyBook : Book.smth { } }
When same-named namespaces exist ( in current scope ) , how to refer any of them ?
C#
I have a working solution for WP8.0 . But I needed to upgrade to get access to WNS . I have succeeded in adding WNS to the upgrade solution in the main menu works . But after Upgrading to wp8.1 ( silverlight ) , I have had some weird errors , that only happens on runtime . As an example it happens in the following user...
< UserControlxmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : i= '' clr-na...
xaml parse error on interaction triggers wp8.1 ( silverlight )
C#
what 's the difference for the following two ways to define namespace ? in some where I may have Both need to do the same to use class AA by using A.B.C ; Can I use C.AA a ; to specify the AA class in C namespace or I have to use the fall namespace convention : A.B.C.AA a ; to avoid possbile confliction ?
namespace A.B.C { public class AA { } } namespace A { namespace B { namesapce C { public class AA { } } } } namespace A { //some classes } namespace A.B { //some classes } namespace A { namespace B { //some classes } }
C # namespace questions
C#
I 'm trying to create an extension VSPackage for VS2017 ( in C # ) which would convert binary data to XML , opens that in the default VS XML editor and XML language service , and then converts it back to binary upon saving.However , I have troubles to line out which steps would be required for this . I thought of the f...
private MyPackage _package ; // Filled via constructorprivate IServiceProvider _serviceProvider ; // Filled via SetSitepublic int CreateEditorInstance ( uint grfCreateDoc , string pszMkDocument , string pszPhysicalView , IVsHierarchy pvHier , uint itemid , IntPtr punkDocDataExisting , out IntPtr ppunkDocView , out IntP...
VSX : How can I reuse the existing XML editor to handle binary files converted to XML ?
C#
I have a byte array that looks something like this : My end goal is to split this array into sub array 's anytime I see the sequence { 0x13 , 0x10 } . So my desired result on the example array would be : Ideally , I would also need to know that the final array , { 0x75 , 0x3a , 0x13 } , did not end with the search sequ...
byte [ ] exampleArray = new byte [ ] { 0x01 , 0x13 , 0x10 , 0xe2 , 0xb9 , 0x13 , 0x10 , 0x75 , 0x3a , 0x13 } ; { 0x01 } { 0xe2 , 0xb9 } { 0x75 , 0x3a , 0x13 }
How to properly search and parse an array using a sequence of elements as the target
C#
I 'm in a situation where two calls at the same time write to the session ( of an asp.net core application running on the old framework ) , and one of the session variables gets overwritten.Given the following controller code , assume that the long session gets called first , 200 ms later the short session gets called ...
[ HttpPost ( `` [ action ] '' ) ] public async Task < IActionResult > TestLongSession ( ) { HttpContext.Session.SetString ( `` testb '' , `` true '' ) ; // If we do this delay BEFORE the session ( `` testb '' ) is set , then all is fine . await Task.Delay ( 1000 ) ; return Ok ( ) ; } [ HttpPost ( `` [ action ] '' ) ] p...
ASP.NET session is overwritten
C#
I 'm slowly getting my head around delegates , in that the signature of the delegate must match that of the method it is delegating too.However , please review the following code . I am now stumped at this point , because the delegate returns void ( as that is what SaveToDatabase ( ) is ) but , it 's clearly returning ...
public static void Save ( ) { ThreadStart threadStart = delegate { SaveToDatabase ( ) ; } ; new Thread ( threadStart ) .Start ( ) ; } private static void SaveToDatabase ( ) { }
How does the keyword delegate work compared to creating a delegate
C#
Hello I 'm try to remove special characters from user inputs . At the end I 'm turning it back to a string . My code only removes one special character in the string . Does anyone have any suggestions on a easier way instead
public void fd ( ) { string output = `` '' ; string input = Console.ReadLine ( ) ; char [ ] charArray = input.ToCharArray ( ) ; foreach ( var item in charArray ) { if ( ! Char.IsLetterOrDigit ( item ) ) { \\\CODE HERE } } output = new string ( trimmedChars ) ; Console.WriteLine ( output ) ; }
Special characters Regex
C#
From https : //msdn.microsoft.com/en-us/library/d5x73970.aspx When applying the where T : class constraint , avoid the == and ! = operators on the type parameter because these operators will test for reference identity only , not for value equality . This is the case even if these operators are overloaded in a type tha...
public static void OpTest < T > ( T s , T t ) where T : class { System.Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` target '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( `` target '' ) ; string s2 = sb.ToString ( ) ; OpTest < string > ( s1 , s2 ) ; } static void Main ( ) {...
C # generic types equality operator
C#
How would I get change this snippet to correctly add an instance of A to a List < A > , B to a List < B > , etc . ? The exception is thrown because , while the Add ( ) is found by the binder , it passes in dynamic which fails overload resolution . I prefer not to change the above to use reflection , or at least to mini...
// someChild 's actual type is Aobject someChild = GetObject ( ) ; // collection 's actual type is List < A > though method below returns objectdynamic list = GetListFromSomewhere ( ... ) ; // code below throws a RuntimeBinderExceptionlist.Add ( somechild ) ;
How to add a T to List < T > where List < T > masquerades as 'dynamic ' and T as 'object ' ?
C#
To my surprise I have discovered a powerful feature today . Since it looks too good to be true I want to make sure that it is not just working due to some weird coincidence.I have always thought that when my p/invoke ( to c/c++ library ) call expects a ( callback ) function pointer , I would have to pass a delegate on ...
[ UnmanagedFunctionPointer ( CallingConvention.Cdecl ) ] public delegate int KINSysFn ( IntPtr uu , IntPtr fval , IntPtr user_data ) ; [ DllImport ( `` some.dll '' , EntryPoint = `` KINInit '' , ExactSpelling = true , CallingConvention = CallingConvention.Cdecl ) ] public static extern int KINInit ( IntPtr kinmem , KIN...
Delegate on instance method passed by P/Invoke
C#
Is there a way in C # to disable keyword 's functionality in code ? In my case I want to define one of my enum items as float which obviously makes Visual Studio a bit confused : )
public enum ValidationType { email , number , float , range }
C # disable keyword functionality
C#
What does = > means ? Here 's a code snap :
Dispatcher.BeginInvoke ( ( Action ) ( ( ) = > { trace.Add ( response ) ; } ) ) ;
What does '= > ' mean ?
C#
I have the below method where I need to check for some certain strings which could be in any case and then remove them . Just wondered if there was a better performing way ?
private void MyMethod ( string Filter ) { //need to remove < Filter > and < /Filter > case in-sensitive var result = Filter.ToLower ( ) .Replace ( `` < filter > '' , '' '' ) ; result = Filter.ToLower ( ) .Replace ( `` < /filter > , '' '' ) ; ... ... ... ... ... ... ... ... ... }
Out of curiosity - is there a better performing approach to do this string replace ?
C#
Can anyone think of good Resharper pattern that will detect the following bug : I 've tried creating a pattern but I ca n't work out how to quickly handle all types of arithmetic ( e.g . + , - , * etc ) , and any nullable type ( e.g . Nullable < int > , Nullable < decimal > , Nullable < double > etc ) . Also I ca n't h...
decimal ? x = null ; decimal ? y = 6M ; var total = x + y ; Console.WriteLine ( total ) ; // Result is null
Resharper pattern to detect arithmetic with nullable types
C#
This is homework ! ! ! Please do not interpret this as me asking for someone to code for me.My Program : http : //pastebin.com/SZP2dS8D This is my first OOP . The program works just fine without user input ( UI ) , but the implementation of it renders my design partially ineffective . I am not using a List collection b...
Please enter the quarter : ( user input ) Would you like to add a course ? while ( true ) Enter Course/Credits/Grade//new Course information populated with user input transcript.AddCourse.to specific Quarter ( ( Fall 2013 ) new Course ( `` Math 238 '' , 5 , 3.9 ) ) ; transcript.AddCourse.to specific Quarter ( ( Fall 20...
C # : Bad design of class ( first OOP )
C#
In my BL ( will be a public API ) , I am using ICollection as the return types in my Find methods , like : Note the use of ICollection instead of Collection < > .Now in my GUI , I need to cast the results back to Collection , like : This is because I need to use some Collection < > specific methods on my returned list ...
public static ICollection < Customer > FindCustomers ( ) { Collection < Customer > customers = DAL.GetCustomers ( ) ; return customers ; } Collection < Customer > customers = ( Collection < Customer > ) BL.FindCustomers ( ) ;
Question regarding return types with collections
C#
I have the following in my controller ; This only occurs 4 times but it bugs me that I have the code repeated 4 times.I then have a BaseController that then grabs the parameters and does stuff with them ; I 'd like to be able to do away with the Post ActionResult 's and have a single one in a base controller say.Is thi...
public ActionResult CocktailLoungeBarAttendant ( ) { return View ( ) ; } [ HttpPost ] public ActionResult cocktailLoungebarattendant ( string name , string email , string phone ) { return View ( ) ; } public ActionResult merchandisecoordinator ( ) { return View ( ) ; } [ HttpPost ] public ActionResult merchandisecoordi...
Create common ActionResult
C#
tl ; dr : Overriding a generic iterator method in a constructed derived class results in a BadImageFormatException being thrown when compiled with Visual Studio 2010 ( VS2010 ) , regardless of .NET version ( 2.0 , 3.0 , 3.5 or 4 ) , platform or configuration . The problem is not reproducible in Visual Studio 2012 ( VS2...
public class Program { public static void Main ( string [ ] args ) { foreach ( var item in new ScrappyDoo ( ) .GetIEnumerableItems ( ) ) Console.WriteLine ( item.ToString ( ) ) ; } } public class ScoobyDoo < T > where T : new ( ) { public virtual IEnumerable < T > GetIEnumerableItems ( ) { yield return new T ( ) ; } } ...
Overriding generic iterator results in BadImageFormatException when compiled with Visual Studio 2010
C#
I 've considered 2 cases : Ideone : http : //ideone.com/F8QwHYand : Ideone : http : //ideone.com/hDTcxXThe question is why does order of fields actually matter ? Is there any reason for this or it 's just simply because it is ( such is the design ) .If the reason is just that anonymus types are not supposed to be used ...
var a = new { a = 5 } ; var b = new { a = 6 } ; Console.WriteLine ( a.GetType ( ) == b.GetType ( ) ) ; // True var a = new { a = 5 , b = 7 } ; var b = new { b = 7 , a = 6 } ; Console.WriteLine ( a.GetType ( ) == b.GetType ( ) ) ; // False
Why does compiler generate different classes for anonymous types if the order of fields is different
C#
The following is a simplified version of the problem I 'm having : The comments are the values from the watch window in Visual Studio 2017However if I enter : in the watch window , I get : So how come I can cast it in the watch window and it works , but if I do it in the code it evaluates to null ?
var list = new List < int > { 1 , 2 , 3 , 4 , 5 } ; // list Count = 5 System.Collections.Generic.List < int > var obj = list as object ; // obj Count = 5 object { System.Collections.Generic.List < int > } var enumerable = obj as IEnumerable < object > ; // enumerable null System.Collections.Generic.IEnumerable < object...
Casting object to IEnumerable < object >
C#
i ca n't understand the difference between a simple bare and I know I can use it only if i have a +1 overloaded ctor , but I ca n't understand the advantages of defining the parameterless constructor this way .
Public ClassName ( ) { } Public ClassName ( ) : this ( null ) { }
When and why should I use ClassName : this ( null ) ?
C#
Simplified , i have these 2 Extension method : And here is where i use them : I have more GetString ( ) extensions.My try { ... } catch { ... } is getting large and basically i search for ways to shorten it down to 1 catch that calls the extension based on the type of the exception.Is there a way to call the right exte...
public static class Extensions { public static string GetString ( this Exception e ) { return `` Standard ! ! ! `` ; } public static string GetString ( this TimeoutException e ) { return `` TimeOut ! ! ! `` ; } } try { throw new TimeoutException ( ) ; } catch ( Exception e ) { Type t = e.GetType ( ) ; //At debugging th...
Calling extension method 's overload with derived type
C#
While removing some obsolete code I came across an unexpected scenario , recreated below : Based in the output it seems that functions deprecated with a warning are permitted to call functions deprecated with an error and the code will execute . My expectation was that I would see a compiler error complaining that the ...
class Program { static void Main ( string [ ] args ) { ViableMethod ( ) ; Console.WriteLine ( `` '' ) ; SoftDeprecatedMethod ( ) ; //Compiler warning //HardDeprecatedMethod ( ) ; //Ca n't call that from here , compiler error Console.ReadKey ( true ) ; } public static void ViableMethod ( ) { Console.WriteLine ( `` Viabl...
Deprecation behavior using the [ Obsolete ] attribute
C#
EDIT : see my update below on my stance on Null in C # 8.0 before giving me options to patterns and suchOriginal questionI am trying to upgrade my base libraries to be `` null enabled '' , aka using the C # 8.0 < Nullable > enable < /Nullable > flag.When trying to work with abstractions , and in specific generics , I r...
public static Func < TResult > ToFunc < TResult > ( this Action action ) = > ( ) = > { action ( ) ; return default ; } ; public static Func < TResult ? > ToFuncClass < TResult > ( this Action action ) where TResult : class = > ( ) = > { action ( ) ; return null ; } ; public static Func < TResult ? > ToFuncStruct < TRes...
Generics and Nullable ( class vs struct )
C#
When calling a method with a ref or out parameter , you have to specify the appropriate keyword when you call the method . I understand that from a style and code quality standpoint ( as explained here for example ) , but I 'm curious whether there is also a technical need for the keywords to be specified in the caller...
static void Main ( ) { int y = 0 ; Increment ( ref y ) ; // Is there any technical reason to include ref here ? } static void Increment ( ref int x ) { x++ ; }
Is there a technical reason for requiring the `` out '' and `` ref '' keywords at the caller ?
C#
Could someone point out why this could be happening : I am using NHibernate and the Linq provider for it.The code that fails is listed here : Debugging shows that sequence ( which is an IQueryable < T > ) after this contains 2 elements , which were added to the database.I expect the first Where statement to yield all e...
var sequence = session.Query < T > ( ) ; var wtfSequence = sequence.Where ( x = > true ) ; var okaySequence = sequence.Where ( x = > x.Id > 0 ) ; NHibernate : select cast ( count ( * ) as INTEGER ) as col_0_0_ from `` BinaryUnitProxy_IndicatorUnitDescriptor '' binaryunit0_ where @ p0='true ' ; @ p0 = 'True ' [ Type : S...
C # strange lambda behavior
C#
I am using Xamarin.Forms and I have 2 pages , one is a List View , the other is a just a view I am using as a filter for the List View . I am currently using Navigation.PushAsync to display this page , my question is , is there away to present it like a side menu ? I know there is Master Detail View which I am already ...
public partial class PatientsPage : ContentPage { public PatientsPage ( ) { InitializeComponent ( ) ; ToolbarItems.Add ( new ToolbarItem ( `` Filter '' , `` filter.png '' , ( ) = > { openFilter ( ) ; } ) ) ; } public async void openFilter ( ) { await Navigation.PushAsync ( new PatientFiltersPage ( ) ) ; } }
Xamarin.Forms Navigation.PushAsync as Side Menu
C#
I am using the debugger to step through my code . The code file I ’ m in has usings at the top , including for exampleIn Visual Studio 2008 this used to apply to the Watch window while debugging , so I could use extension methods such as .First ( ) and .ToArray ( ) in the watch window.For some reason , this has stopped...
using System.Linq ; System.Linq.Enumerable.ToArray ( blah )
Watch window stopped accepting some usings
C#
The following code does n't compile ( error CS0123 : No overload for 'System.Convert.ToString ( object ) ' matches delegate 'System.Converter < T , string > ' ) : however , this does : In c # 4 , co/contra-variant delegates can be assigned to each other , and delegates can be created from co/contra-variant methods , so...
class A < T > { void Method ( T obj ) { Converter < T , string > toString = Convert.ToString ; // this does n't work either ( on .NET 4 ) : Converter < object , string > toString2 = Convert.ToString ; Converter < T , string > toString3 = toString2 ; } } class A < T > { void Method ( T obj ) { // o is a T , and Convert....
How is method group overload resolution different to method call overload resolution ?
C#
I have csv file with 30 000 lines . I have to select many values based on many conditions , so insted of many loops and `` if 's '' i decided to use linq . I have written class to read csv . It implements IEnumerable to be used with linq . This is my enumerator : It 's working , but it 's slow . Let 's say i want to se...
class CSVEnumerator : IEnumerator { private CSVReader _csv ; private int _index ; public CSVEnumerator ( CSVReader csv ) { _csv = csv ; _index = -1 ; } public void Reset ( ) { _index = -1 ; } public object Current { get { return new CSVRow ( _index , _csv ) ; } } public bool MoveNext ( ) { return ++_index < _csv.TotalR...
Is possible to change search method in LINQ ?
C#
When im passing Bmp as stream , function always return , but file saving on disk correctly.When I load bpm from disk , function return correct MD5 . Also passing `` new Bitmap ( int x , int y ) ; '' with different value return same MD5.Why its happening ? Can somebody explain this strange behaviour ?
D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E public static string GetMD5Hash ( ) { Bitmap Bmp = new Bitmap ( 23 , 46 ) ; // using ( Graphics gfx = Graphics.FromImage ( Bmp ) ) using ( SolidBrush brush = new SolidBrush ( Color.FromArgb ( 32 , 44 , 2 ) ) ) { gfx.FillRectangle ( brush , 0 , 0 , 23 , 46 ) ; } using ( va...
Problem with counting MD5 from bitmap stream C #
C#
I 've got the following situation : There are two related types . For this question , I 'll use the following simple types : So that one Person might have multiple Accounts ( i.e. , multiple Accounts would reference the same PersonId ) .In our database , there are tens of thousands of persons , and each have 5-10 accou...
public class Person { public Guid Id { get ; set ; } public int status { get ; set ; } } public class Account { public Guid AccountId { get ; set ; } public decimal Amount { get ; set ; } public Guid PersonId { get ; set ; } } var query = from p in personList join a in accountList on p.Id equals a.PersonId where a.Amou...
Retrieving large amount of records under multiple limitations , without causing an out-of-memory exception
C#
Suppose I have the following : In what situation ( s ) would there be an advantage to using MyClassB over MyClassA ?
public class MyElement { } [ Serializable ] [ StructLayout ( LayoutKind.Sequential ) ] struct ArrayElement { internal MyElement Element ; } public class MyClass { internal MyElement ComputeElement ( int index ) { // This method does a lengthy computation . // The actual return value is not so simple . return new MyElem...
When to use an array of a value type containing a reference types over an array of a reference type ?
C#
Given the following C # code : The question is : what is causing the type of i to be correctly inferred as an int ? This is not at all obviuous , as array2D is a rectangular array . It does not implement IEnumerable < int > . It also implements a GetEnumerator ( ) method , which returns a System.Collections.IEnumerator...
int [ , ] array2D = new int [ 10 , 10 ] ; int sum = 0 ; foreach ( var i in array2D ) { sum += i ; }
Why does foreach ( var i in array2D ) work on multidimensional arrays ?
C#
is it possible to differ the variable I 'm assigning to depending on a condition ? The issue I came across is wanting to do this : Instead ofWhich results in the following error Error CS0131 The left-hand side of an assignment must be a variable , property or indexerSo I was wondering if there was a way to do this to c...
( bEquipAsSecondary ? currentWeaponOffhand : currentWeaponMainhand ) = weaponToSwitchTo ; if ( bEquipAsSecondary ) { currentWeaponOffhand = weaponToSwitchTo ; } else { currentWeaponMainhand = weaponToSwitchTo ; }
Is there a way to use a ternary operator - or similar method - for picking the variable to assign to ?