lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I wrote a class that detects what is the current Excel theme.Get Excel current office theme : Then based on the value of themeCode , I can determine what the current Excel theme is : My question : How can I detect when the user , during Excel Running , change the Office Theme from the Excel Options ? In Another way , i...
//Declarationstring officeVersion ; int themeCode ; // Get Office Version firstofficeVersion = `` 16.0 '' ; // Goto the Registry Current VersionRegistryKey rk = Registry.CurrentUser.OpenSubKey ( @ '' Software\Microsoft\Office\ '' + officeVersion + @ '' \Common '' ) ; // Get Stored ThemethemeCode = ( int ) rk.GetValue (...
C # Visual Studio Excel Add-in : How can I detect Excel Office Theme Change ?
C#
Are the following C # -statementsandequivalent or are there any numerical caveats ?
double a , b = ... ; ! ( a > b ) a < = b
Is `` not > '' equivalent to `` < = '' for a double
C#
Is there any practical difference between these two extension methods ? I was poking around in Extension Overflow and I came across the first form , which I have n't used before . Curious what the difference is .
class Extensions { public static void Foo < T > ( this T obj ) where T : class { ... } public static void Foo ( this object obj ) { ... } }
Is there any practical difference between an extension method on < T > or on Object ?
C#
Im in the middle of porting my C # code to a F # library.I have the following interfaces/classes in my C # library : I have tried to port this to F # , this is what I 've come up with : The problem is , I need to call this F # library from my C # application.Before , when using the C # classes , I could do the followin...
public interface IMatch < out T > where T : IGame { IEnumerable < T > Games { get ; } } public interface IGame { string Name { get ; } } public class SoccerMatch : IMatch < SoccerGame > { public SoccerMatch ( IEnumerable < SoccerGame > games ) { Games = games ; } public IEnumerable < SoccerGame > Games { get ; } } publ...
Why does n't type implemented in f # behave the same as C # types when called from C # application ?
C#
I have two tables in my database : TPM_AREAS and TPM_WORKGROUPS . There exists a many-to-many relationship between these two tables , and these relationships are stored in a table called TPM_AREAWORKGROUPS . This table looks like this : What I need to do is load all these mappings into memory at once , in the quickest ...
var foo = ( from aw in context.TPM_AREAWORKGROUPS select aw ) ; var allWG = ( from w in context.TPM_WORKGROUPS.Include ( `` TPM_AREAS '' ) where w.TPM_AREAS.Count > 0 select w ) ; // Loop through this enumeration and manually build a mapping of distinct AREAID/WORKGROUPID combinations . using ( DbCommand cmd = conn.Cre...
Is there a quick way to get every association between two entities ?
C#
I 'm a contributer to the open source project Rubberduck , and looking to add support for the standalone VB6 IDE ( it currently supports VBA ) .One piece of information we need from the IDE is the mode it 's currently in - Design , Break or Run . On the VBA side , this is exposed by the extensibility API , however this...
public class Test { private const string DllName = `` vba6.dll '' ; // Not considering VB5 for now [ DllImport ( DllName ) ] private static extern int EbMode ( ) ; public EnvironmentMode Mode = > ( EnvironmentMode ) EbMode ( ) ; } public enum EnvironmentMode { Run = 0 , Break = 1 , Design = 2 }
How to query the mode of the VB6 IDE from C #
C#
My method returns in many points . I construct newData during execution also in many points . Regardless of where I return I need to save and store constructed result . Not to miss `` return '' I just surrounded the code with try-finally block so now I 'm sure that newData will be stored.But I do n't catch any exceptio...
List < X > newData = new List < X > ( ) ; try { ... . update newData ... .. return ; ... .. ... . update newData ... . update newData return ; ... .. return ; } finally { // copy newData to data }
is it good to use try-finally just to make sure that something is performed when method finished ?
C#
In the interface , I saw the following I want to know the meaning of `` new '' here .
public interface ITest : ITestBase { new string Item { get ; set ; } }
what the new mean in the following
C#
I have a linux ( ubuntu server 14.04 ) machine with 250 ips . When I run my c # code in mono , it only retrieves 50 ips.All ips are configured correctly , I have the same code in java , and all 250 ips are found , and can be bound to.I have tried : andboth return 50 ips ? So , my question , is there a limit in c # on h...
Dns.GetHostByName ( Dns.GetHostName ( ) ) .AddressList ; Dns.GetHostAddresses ( string.Empty ) ;
C # - Machine has 250 ips , I can only retrieve 50 from code
C#
I 'm receiving an error , `` unable to convert string to int ? '' . Which I find odd , I was under the notion when you utilize PropertyInfo.SetValue it should indeed attempt to use that fields type . The above would attempt to implement default ( T ) on the property according to PropertyInfo.SetValue for the Microsoft ...
// Sample : property.SetValue ( model , null , null ) ; // Sample : property.SetValue ( model , control.Value , null ) ; // Sample : PropertyInfo [ ] properties = typeof ( TModel ) .GetProperties ( ) ; foreach ( var property in properties ) if ( typeof ( TModel ) .Name.Contains ( `` Sample '' ) ) property.SetValue ( mo...
Holy Reflection
C#
I 'm tying to extract the header and a 2 or 3 digit ISO 639 code from a string.The general format of a valid string is : header + < special char > + < 2 or 3 digit code > + ( < special char > forced ) The last section < special character > forced is optional and may or may not be present but if present forced must be p...
name.engname-engname ( eng ) name ( fri ) _engname ( fri ) ( eng ) name.eng.forcedname ( eng ) .forcedname. ( eng ) .forcedname.fri.eng.forcedname ( fri ) .eng.forcedname . ( fri ) .eng_forcedname-fri-eng.forcedname_ ( fri ) _eng.forcedname ( fri ) _eng.forcedname ( friday ) _eng_forcedname ( fri ) ( eng ) .forced name...
Extracting codes with optional special characters from a string using Regex in C #
C#
I have two classes : In a method which should returns an object of type Table , I try to filter an object of type Table with the Where-Statement and return this object after filtering.My problem is the cast of the resulting IEnumerable . Conversion with ( Table ) throws an InvalidCastException Additional information : ...
public class Row : Dictionary < string , string > { } public class Table : List < Row > { } Table table = new Table ( ) ; table = tableObject.Where ( x = > x.Value.Equals ( `` '' ) ) .ToList ( ) ; return table ;
How can I cast a List into a type which inherits from List < T > ?
C#
I want to create a base class Student with a method changeName inside of it . I want studentclasses derived from the base class Student , such as collegestudent etc . I want to be able to change the names of the students.I have this code : I want to know if its possible to change the public virtual void changeName para...
public abstract class Student { public virtual void changeName ( CollegeStudent s , string name ) { s.firstName = name ; } public abstract void outputDetails ( ) ; } public class CollegeStudent : Student { public string firstName ; public string lastName ; public string major ; public double GPA ; public override void ...
C # method : is there a parameter name to insert 'derived classname ' generically ?
C#
I 'm trying to create a helper function ( for a class ) that accepts 2 objects and compares a property on both classesThese properties are only ever simple types like string , int and boolUsageWhat i have so farObviously the code above does n't work
Compare ( widget1 , widget2 , x = > x.Name ) private void CompareValue < T > ( Order target , Order source , Func < Order , T > selector ) { if ( target.selector ! = source.selector ) { // do some stuff here } }
How to create a method that accepts 2 objects of the same Type , a property , and compares the values
C#
I have a regex that I 've verified in 3 separate sources as successfully matching the desired text.http : //regexlib.com/RETester.aspxhttp : //derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx , http : //sourceforge.net/projects/regextester/But , when I use the regex in my code . It does...
string SampleText = `` starttexthere\r\nothertexthereendtexthere '' ; string RegexPattern = `` ( ? < =starttexthere ) ( .* ? ) ( ? =endtexthere ) '' ; Regex FindRegex = new Regex ( @ RegexPattern ) ; Match m = FindRegex.Match ( SampleText ) ;
C # Regex Pattern Conundrum
C#
On C # , I 'm printing the JSONified string that I 'm sending to the console , and it reads asThen I do this to convert it to a byte array and send itAnd on the node.js side , I get this when console.logging res.body : That does n't look like valid JSON . What happened ? How can I send and receive the proper data ?
{ `` message '' : `` done '' , `` numSlides '' : 1 , `` slides '' : [ { `` num '' : 1 , `` key '' : `` 530d8aa855df0c2d269a5a5853a47a469c52c9d83a2d71d9/1slide/Slide1_v8.PNG '' } ] , `` bucket '' : `` xx.xxxxxxxxxx '' , `` error '' : null , `` wedge '' : false , `` tenant '' : null , `` name '' : null } WebRequest reque...
Converting an object into Json in C # and sending it over POST results in a corrupt object ?
C#
By definition Nullable < > is a struct but when I call some generic function , it behaves like it 's an object.So the parameter is seen as an object instead of a struct.Any idea of what 's happening , am I misunderstanding the meaning of struct ? Is there a way to dispach Nullable < T > or T and object as different kin...
class GenController { public void Get < T > ( T id ) where T : struct { Console.Write ( `` is struct '' ) ; } public void Get ( object obj ) { Console.Write ( `` is object '' ) ; } } long param1 = 1234 ; new GenController ( ) .Get ( param1 ) ; // output is `` is struct '' as expectedlong ? param2 = 1234 ; new GenContro...
Is `` long ? '' really a struct ?
C#
I need to make a method for displaying serial terms based on the number associated with these days.So , I base myself for each day ( term ) , set a specific number . Sun = 1 , Mon = 2 , Tues = 4 , Wed = 8 , Thu = 16 , Fri = 32 , Sat = 64If the user has chosen all eg working days , Mon - Fri = 62 , or weekend Sat - Sun ...
var terminDates = dataAccess.GetTerminDate ( personal.LPE_Nr , date , DateTime.DaysInMonth ( date.Year , date.Month ) ) ; for ( int i = 0 ; i < terminDates.Count ; i++ ) { T_TERMINE _TERMINE = new T_TERMINE ( ) ; List < T_TERMINE > terminList = dataAccess.GetListTermins ( personal.LPE_Nr , terminDates [ i ] ) ; string ...
Showing serial terms using the complex bit masks
C#
I 've been using the HttpClient in code for a while now and have always felt its use of Uris has resulted in some brittleness in my implementation . Most of our service endpoint base addresses are in the app./web.config . As a result , they can be easily changed . I 've found that when using these endpoint strings to g...
var service = settings.GetValue ( `` ServiceBaseUrl '' ) ; var serviceUri = ! service.EndsWith ( `` / '' ) ? new Uri ( service + `` / '' ) : new Uri ( service ) ; _client = new HttpClient { BaseAddress = serviceUri } ; `
Using Uri strings that may or may not have trailing / 's
C#
I ca n't get my head round this , threads all over SO state i 'm doing all the right things but clearly I must have missed something ... Given these two object defs ... And then context with the appropriate relationship configuration ... Why when I do this ... Do I get this exception ... The operation failed : The rela...
public class Invoice { [ Key ] public int Id { get ; set ; } [ ForeignKey ( `` Block '' ) ] public int ? BlockingCodeId { get ; set ; } public virtual BlockingCode Block { get ; set ; } ... } public class BlockingCode { [ Key ] public int Id { get ; set ; } public virtual ICollection < Invoice > Invoices { get ; set ; ...
EF 0..1 to Many Relationship updates
C#
Say I have this simple entity : The entity framework can infer by convention that the PersonID field is the primary key . However , if I give the model builder this class : Would that improve startup performance ? My thought was it might allow EF to do less reflecting and startup the app faster but I do n't know how it...
public class Person { public int PersonID { get ; set ; } public string Name { get ; set ; } } public class PersonCfg : EntityTypeConfiguration < Person > { public PersonCfg ( ) { ToTable ( `` Person '' , `` Person '' ) ; HasKey ( p = > p.PersonID ) ; } }
Is EntityFramework performance affected by specifying information like primary key ?
C#
At work I ran into a strange problem , where a loop I expected to terminate was actually running indefinitely.I traced the problem back to a use of Select.Interestingly , the loop terminated as expected when I added a .ToList ( ) right after the Select . I boiled it down to a small example.While I do n't have to deal w...
class WrappedBool { public WrappedBool ( bool inner ) { InnerBool = inner ; } public bool InnerBool { get ; set ; } = false ; } // remove .ToList ( ) here and the following loop will go infiniteIEnumerable < WrappedBool > enumerable = new List < bool > ( ) { false , true , false } .Select ( b = > new WrappedBool ( b ) ...
Why does Select turn my while loop into an infinite loop ?
C#
Can I do this using using var : or should I do this : or can I just go without disposing because the iterator is an IAsyncDisposable and the await foreach will do it for me ?
await foreach ( var response in _container.GetItemQueryStreamIterator ( query ) ) { using var safeResponse = response ; //use the safeResponse } await foreach ( var response in _container.GetItemQueryStreamIterator ( query ) ) { try { //use response } finally { response ? .Dispose ( ) ; } } await foreach ( var response...
How to safely dispose of IAsyncDisposable objects retrieved with await foreach ?
C#
Here I 'm working with a Java to C # sample app translation that involves cryptography ( AES and RSA and so on ... ) At some point in Java code ( the one that actually works and being translated to C # ) , I 've found this piece of code : After some googling ( here ) , I 've seen that this is a common behaviour mainly ...
for ( i = i ; i < size ; i++ ) { encodedArr [ j ] = ( byte ) ( data [ i ] & 0x00FF ) ; j++ ; } // where data variable is a char [ ] and encodedArr is a byte [ ]
Why the need of a bitwise `` and '' for some char to byte conversions in Java ?
C#
I 'm doing a small assignment for school and I 'm having a bit of trouble . The purpose of the program is to sum up the roll of 2 random numbers 36000 times . The numbers should be in the range of 1-6 ( to simulate dice ) . We 're then to count the frequency of each summed value and display it to the console.Seemed eas...
using System ; public class DiceRollUI { public static void Main ( string [ ] args ) { DiceRoll rollDice = new DiceRoll ( ) ; Random dice1 = new Random ( ) ; //dice 1 Random dice2 = new Random ( ) ; //dice 2 int len = 36000 ; while ( len > 0 ) { rollDice.DiceRange ( ( uint ) dice1.Next ( 1 , 7 ) + ( uint ) dice2.Next (...
Can not get array elements to display correctly C #
C#
I have an interface with two generic parameters , but one of the parameters is expected to be provided by the class implementation.However , another interface have a method that takes an instance of IA as a parameter - however , every instance must be the same ( the same class can take multiples X , but then it will ne...
public interface IA < T , U > { ... } public class X < T > : IA < T , int > { ... } public class Y < T > : IA < T , MyClass > { ... } public interface IB < T , U , V > where U : IA < T , V > { void MyMethod ( U value ) ; } public class Z < T > : IB < T , X < T > , int > { ... } public interface IB < T > { void MyMethod...
How to implement a generic parameter that is n't generic
C#
I have two Forms in my application . They way I call Form 2 is like this : Form 1 : Form 2 : My problem is if the user clicks the Add button , the error message shows ( because the data is invalid or the textboxes are empty ) BUT it closes the form . I only want the user to close the form and pass the data back if the ...
private void btnTest_Click ( object sender , EventArgs e ) { DialogResult result = new System.Windows.Forms.DialogResult ( ) ; Add_Link addLink = new Add_Link ( ) ; result=addLink.ShowDialog ( ) ; if ( result == System.Windows.Forms.DialogResult.OK ) { // } } private void btnAdd_Click ( object sender , EventArgs e ) { ...
Form Closes When it Should n't
C#
i am designing a database and have theory problem , about which solution works better to run queries , to be faster on microsoft sql server or simply more relational.GIVENLets say , we have the following Tables : Congress , Person , Session , Room , and much more.Do n't mind about the given names . These are just some ...
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| Congress | Person | Session | Room | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| CongressID | PersonID | SessionID | RoomID || Name | Name | Name | Name || ... | ... ...
SQL Theory Multiple References
C#
I 'm using the following code to convert radians to degrees and do some arithmetic on the same.The value calculates is inaccurate . I 'm using the same code in Python and the result is quite accurate as follows , How do I get the accurate degrees with c # ? Note : The output is after ( -135 - deg ) % 360 ; The output f...
private double getDegrees ( double rad ) { double deg = rad * Mathf.Rad2Deg ; double degree = ( -135 - deg ) % 360 ; return degree ; } def getDegree ( rad ) : return ( -135 - math.degrees ( rad ) ) % 360 Input : -2.54 Output : 10.750966993188058Input 2.57 Output 77.6960764459401Input -0.62 Output 260.9199271359733Input...
Calculation of degrees is inaccurate
C#
I 'm loading data from a MySQL database into a C # .NET application . The data is held in the database as DBType.Double , but for use in my application I cast to Decimal using Convert.ToDecimal ( ) . The data is positional data used in surveying and can be used to display a 3D model in a Direct3D window.When the Direct...
List < vertex > positions = new List < vertex > ( ) ; using ( MySqlCommand cmd = new MySqlCommand ( `` SELECT x , y , z FROM positionTable ; '' , conn ) ) { MySqlDataReader dr = cmd.ExecuteReader ( ) ; try { while ( dr.Read ( ) ) { vertex position = new vertex ( ) ; position.X = Convert.ToDecimal ( dr [ 0 ] ) ; positio...
Convert.ToDecimal giving different results when DirectX/Direct3D loaded
C#
I currently have this controller function : This currently gives me an error on my view page if I attempt to edit an item with an id of 100 , when there is no user with an id of 100 in the database.What 's the best practice for handling this ? Send them to a Create page , or show a friendly error message ? Should that ...
public ViewResult Edit ( int id ) { //get user from id var user = _adminRepository.GetUser ( id ) ; return View ( user ) ; }
Best practice for attempting to edit an item that does n't exist ?
C#
This C # does n't compile : The complaint from the compiler is : The type 'IdList ' already contains a definition for 'Item'If I comment out the indexer , it compiles.How can I get this to compile ? Rider does n't have a fixit.The unstylish workaround is not to nest the Item class.IDE is Rider 2018.1.4 , Language level...
public class IdList < T > where T : IdList < T > .Item { List < T > List = new List < T > ( ) ; public T this [ int id ] { get = > List [ id ] ; set { } } public class Item { public int id ; // Not shown : id used for equality and hash . } }
Generic class whose parameter extends a nested class
C#
I 'm refactoring a big C # project and it 's only natural to find my snowman 's unused dead code.There 's this function called FooBar ( ) which looks useful since it has a bunch of code inside it . As is obvious , I was trying to find the references to this function using the `` Find All References ( F9 ) '' option and...
~public virtual void FooBar ( ) { < function is empty > } ~ public override void FooBar ( ) { ~ < doing something important here > ~ }
Is the Find All References in Visual Studio good enough to judge if a piece of code is unused ?
C#
I am trying to cast a float into a byte array of length 4 , and then back again . But I it doesn 's seems to work.Here 's what I 've done : I expected fb = 90 , but it 's 1.26E-43.I know that my converter is little endian , so I 've also tried to reverse the array , like this : Then I got the answer fb = 9.0E+15.Any id...
byte [ ] b = BitConverter.GetBytes ( 90 ) ; float fb = BitConverter.ToSingle ( b , 0 ) ; byte [ ] b = BitConverter.GetBytes ( 90 ) ; Array.Reverse ( b ) ; float fb = BitConverter.ToSingle ( b , 0 ) ;
Byte array to float
C#
I 've got 3 C # projects/assemblies , A , B and C. B references A , C references B.In A : In B : In C : This all compiles.If I import the System.Linq namespace in Project C and add the line strings.Select ( s = > s ) ; ( or any LINQ method ) before the call to client.M ( ) , I get a compiler error : The type ' A.Dict '...
using System.Collections.Generic ; namespace A { public class Dict : Dictionary < string , object > { } public class Options : Dict { } } using System.Collections.Generic ; using A ; namespace B { public class Client { public void M ( IDictionary < string , string > d ) { var dict = d.ToDict < Options > ( ) ; } } publi...
Reference required error only when using LINQ
C#
I have a third-party assembly that has a huge struct with lots of members of different types in it . I need to take some of the values from that struct and process them . So I write overloads for different types . I know what I need to do with ints , with chars , etc . And if some value is a key value pair , I know I n...
class Program { static void Main ( string [ ] args ) { } void DoSomething ( int a ) { Console.WriteLine ( `` int '' ) ; } void DoSomething ( char a ) { Console.WriteLine ( `` char '' ) ; } void DoSomething < T , U > ( KeyValuePair < T , U > a ) { DoSomething ( a.Key ) ; } }
Generic method takes KeyValuePair . How do I forward the call to the correct overload taking the Key type ?
C#
So I 'm looking in to extending/adapting an API in my own need . I 'm speaking about the Lego Mindstorms C # API . I 'm building my own kind of API around it ( based on the adapter pattern ) so I can program the robot in a better OO way . Here 's the link about how the API works : Lego Mindstorms EV3 C # APIBut now I '...
await brick.DirectCommand.TurnMotorAtPowerAsync ( OutputPort.A , 50 , 5000 ) ; brick.BatchCommand.TurnMotorAtSpeedForTime ( OutputPort.A , 50 , 1000 , false ) ; brick.BatchCommand.TurnMotorAtPowerForTime ( OutputPort.C , 50 , 1000 , false ) ; brick.BatchCommand.PlayTone ( 50 , 1000 , 500 ) ; await brick.BatchCommand.Se...
Object Chaining vs. Methods in API extension
C#
I have this classand in below mapping , I fill in the value of 'Value ' using a procedure in a Formula ( ) But it returns the error when executing : Is there any way to use procedure in fluent nhibernate ?
public class Bill : EntityBase { public virtual decimal Value { get ; set ; } } public class MapBill : ClassMap < Bill > { public MapBill ( ) { Table ( `` cabrec '' ) ; Map ( m = > m.Value ) .Formula ( `` ( select t.VALOR_IND from ret_vlorind ( 1,1 , cast ( '02/06/1993 ' as Date ) ) as t ) '' ) .CustomType ( typeof ( d...
How to use database procedure in fluent nhibernate mapping
C#
I 've been programming for may years first Delphi and now c # so I thought I knew how overloaded method worked , but apparently not.First some codeI 've added a number to each call to CreateSettings in order for making it easyer to explain.My question as : Call # 1 calls the wrong ( Generic ) version of CreateSettings ...
public enum TestEnum { Option1 , Option2 , Option3 } public class Setting { public Setting ( ) { AddSettings ( ) ; } protected void CreateSetting < TEnum > ( string AName , TEnum AValue ) where TEnum : struct , IComparable , IFormattable { //do stuff } protected void CreateSetting ( string AName , string AValue ) { //d...
How do overloaded methods work
C#
Using simple type likewith object intializers , one can writeBut the following is also accepted by the compiler : Same for int [ ] v = new int [ ] { 1 , 2 , } ; This looks a bit strange ... Did they forgot to reject the additional ' , ' in the compiler or is there a deeper meaning behind this ?
class A { public int X , Y ; } var a = new A { X=0 , Y=0 } ; var a = new A { X=0 , Y=0 , } ; // notice the additional ' , '
Why is the compiler not complaining about an additional ' , ' in Array or Object Initializers ?
C#
I 'm working with RPC ( protobuf-remote ) and I need to do some checking in case the other end ( server ) is down . Let 's say I 've lot 's of RPC methods , like : Is there anyway to change this repetitive null-checking code ? So I could write something like : Which would do null-checking and would create object by it ...
public FirstObj First ( string one , string two ) { if ( rpc == null ) return ( FirstObj ) Activator.CreateInstance ( typeof ( FirstObj ) ) ; return rpc.First ( one , two ) ; } public SecondObj Second ( string one ) { if ( rpc == null ) return ( SecondObj ) Activator.CreateInstance ( typeof ( SecondObj ) ) ; return rpc...
C # Repetitive code with null check
C#
This feels like a simple problem but I 'm having issues . DoSomething ( Vehicle vehicle ) does n't exist , so DoSomething ( vehicle ) throws an error , even though vehicle is `` guaranteed '' to be either Car or Bike . How can I convince the compiler that `` vehicle '' is Bike or Car , so that DoSomething can be run ? ...
DoSomething ( Car car ) ; DoSomething ( Bike bike ) ; public class Car : Vehicle { } public class Bike : Vehicle { } public abstract class Vehicle { } void run ( Vehicle vehicle ) { DoSomething ( vehicle ) ; } DoSomething ( Vehicle vehicle ) { if ( vehicle is Car ) ... etc } DoSomething ( Car car ) { motorwayInfo.Check...
Polymorphic overloading - how to force an abstract type to `` act '' as one of its derived types for the purposes of overloaded parameters ?
C#
I 'm trying to create an expression that extracts strings greater than 125 from a given string input.Please view the link for further reference to my script/data example.DonotFiddle_Regex exampleHere is my current expression attempt ( * ) : From the above expression , the only output is 350A , J380S.However I would lik...
var input = `` YH300s , H900H , 234 , 90.5 , +12D , 48E , R180S , 190A , 350A , J380S '' ; Regex.Matches ( input , @ '' ( ? ! .*\.. * ) [ ^\s\ , ] * ( [ 2-5 ] [ \d ] { 2 , } ) [ ^\s\ , ] * '' ) ) YH300s , H900H , R180S , 190A , 350A , J380S
Extract specific values using Regex Expression
C#
I 'm trying to figure out if there 's a way to do something in C # that 's fairly easy to do in C++ . Specifically , if I have an array of data , I can create a pointer into that data to access a subsection more conveniently.For example , if I have : and I determine that there 's a string at positions 102 to 110 within...
unsigned char buffer [ 1000 ] ; unsigned char *strPtr = & buffer [ 102 ] ; char firstChar = strPtr [ 0 ] ; byte [ 8 ] newArray = & buffer [ 102 ] ;
Way to access subset of array ?
C#
Assume I have the following two classes : I created two mapping classes : This will result in a table Item that has a column UserId and a column OwnerId . When I use KeyColumn ( `` OwnerId '' ) on the HasMany mapping , it works with only the OwnerId column , but I would like to avoid that . Is there a way to tell NHibe...
public class User : Entity { public virtual IList < Item > Items { get ; set ; } } public class Item : Entity { public virtual User Owner { get ; set ; } } public class UserMap : ClassMap < User > { public UserMap ( ) { Id ( x = > x.Id ) ; HasMany ( x = > x.Items ) ; } } public class ItemMap : ClassMap < Item > { publi...
Avoid specifying key column in double linked scenario
C#
Quite often I find myself dealing with a pattern similar to this oneTwo inheritance trees , where there is some kind of mirroring . Each of the subclasses in the left tree has a different subclass in the right tree as sourceThe MappingEnd class : The question is , how to deal with that in the subclasses . Do I hide the...
public class MappingEnd { public NamedElement source { get ; set ; } } public class AssociationMappingEnd : MappingEnd { public new Association source { get ; set ; } } public class AssociationMappingEnd : MappingEnd { public Association associationSource { get { return ( Association ) this.source ; } set { this.source...
Dealing with mirrored inheritance trees
C#
I have a GroupSummary class that has some properties like this in it : Then I have a Dictionary like < string , List < GroupsSummary > For each of these dictionary items I want to find all the distinct addresses but the properties of this class that define a distinct address for me are I know as far as I can say someth...
public class GroupsSummary { public bool FooMethod ( ) { //// } public bool UsedRow { get ; set ; } public string GroupTin { get ; set ; } public string PayToZip_4 { get ; set ; } public string PayToName { get ; set ; } public string PayToStr1 { get ; set ; } public string PayToStr2 { get ; set ; } public string PayToC...
Finding the distinct values of a dictionary
C#
Given the following class definitionSomewhere else in my code , I would like see the attributes on the event.But I am seeing only BrowsableAttribute in that attributes collection.How can I get the field : NonSerialized attribute info ?
public class MyClass { [ System.ComponentModel.Browsable ( true ) ] [ field : NonSerialized ] public event EventHandler MyEvent ; } var attributes = typeof ( MyClass ) .GetEvents ( ) .SelectMany ( n = > n.GetCustomAttributes ( true ) ) ;
Inspecting the attributes on the generated field behind a field-like event
C#
The Students object has Name and Weight key-value pairs.In the ToDictionary method , t variable is of type IEnumerable < IGrouping < K , T > > . That is , IEnumerable < IGrouping < int , Students > > Why are the Key values returned by t= > t.Key and t= > t.Select ( **x= > x.Key** ) different ? They both use the same t ...
var Students = new Dictionary < string , int > ( ) ; Students.Add ( `` Bob '' , 60 ) ; Students.Add ( `` Jim '' , 62 ) ; Students.Add ( `` Jack '' , 75 ) ; Students.Add ( `` John '' , 81 ) ; Students.Add ( `` Matt '' , 60 ) ; Students.Add ( `` Jill '' , 72 ) ; Students.Add ( `` Eric '' , 83 ) ; Students.Add ( `` Adam '...
Difference between the returned values of two selector functions in this code
C#
IN THE LAST PART I WROTE THE working solution : I have this stored procedure in SQL Server : and I am passing the parameters but I can not retrieve the SELECT part I need to retrieve B , M , V of Select B , M , V alsoTHIS IS THE WOKING SOLUTION THANKS TO THE HELP I GOT HERE :
alter PROCEDURE [ dbo ] . [ ProcedureName ] @ v nvarchar ( 10 ) , @ L NVarChar ( 2 ) ASBEGIN SET NOCOUNT ON ; SELECT B , M , V FROM XXXX WHERE V = @ v and L = @ LEND SqlCommand Cmd = new SqlCommand ( `` ProcedureName '' , cnn ) ; Cmd.CommandType = CommandType.StoredProcedure ; Cmd.Parameters.Add ( `` @ v '' , SqlDbType...
How to send and receive parameters to/from SQL Server stored procedure
C#
I 'm writing a program in which the user can type in some informations about a customer and then open a MS Word model ( *.dotx ) . After that he can directly archive it with another program . So I click on a button which I created for MS Word and then it should open the other program ( the archive program ) and pass th...
Process p = new Process ( ) ; p.StartInfo.Arguments = `` Word `` + secondArgument ; p.StartInfo.FileName = fileName ; p.Start ( ) ; string [ ] args = Environment.GetCommandLineArgs ( ) ;
How to avoid that a string splits on every whitespace in command line
C#
With C # 6 came some new features , including getter-only auto-properties and property-like function members.I 'm wondering what are the differences between these two properties ? Is there any reason why I 'd prefer one to another ? I know that { get ; } = can only be set by a static call or a constant value and that =...
public class Foo { public string Bar { get ; } = `` Bar '' ; public string Bar2 = > `` Bar2 '' ; }
Readonly getters VS property-like functions
C#
Consider the following code from a standard System.Windows.Forms.FormIt produces this result : Why are the red and blue lines showing up in the incorrect order , and how can this be fixed ?
protected override void OnPaint ( PaintEventArgs e ) { base.OnPaint ( e ) ; Rectangle test = new Rectangle ( 50 , 50 , 100 , 100 ) ; using ( LinearGradientBrush brush = new LinearGradientBrush ( test , Color.Red , Color.Blue , 0f ) ) { e.Graphics.DrawRectangle ( new Pen ( brush , 8 ) , test ) ; } }
LinearGradientBrush does not render correctly
C#
Scratching my head . What 's wrong with the following statement ? encrypt is bool , both of the functions Encryption.Encrypt and Encryption.Decrypt have the same type Func < string , string > , but it tells me that : CS0173 Type of conditional expression can not be determined because there is no implicit conversion bet...
var EncFunc = ( encrypt ? Encryption.Encrypt : Encryption.Decrypt ) ;
Why compiler ca n't determine the type of operands in this case ?
C#
An event can contain many handlers which are defined using delegate , my current understanding is that delegate is just an abstraction of function pointer . Since an event , which associated with a delegate type , can add / remove many delegates into it , and composite pattern treats a composite object the same as the ...
composite.onTriggered ( ) ; // Internally : // foreach ( handler in composite ) // { // handler.onTriggered ( ) ; // } class Counter { public event EventHandler ThresholdReached ; protected virtual void OnThresholdReached ( EventArgs e ) { EventHandler handler = ThresholdReached ; // So what 's the point of this line ?...
Can I say that the relation between events and delegates adopts composite pattern ?
C#
For example : -I 'm looking for a way to test this before runtime , ideally in an automated test isolated from the database.I spent some time trawling through MSDN trying to find how to instantiate my own QueryProvider , but my Google-fu appears to be failing me today.Thanks in advance !
// This one will be converted to SQL no problemExpression < Func < Foo , bool > > predicate = x = > x.Name = `` Foo '' ; // This one will throw a NotSupportedException because the QueryProvider// does n't support reference comparisonsExpression < Func < Foo , bool > > predicate = x = > x == someOtherFoo ; // This one d...
Is it possible to test whether a given expression can be converted to SQL *without* connecting to a SQL database ?
C#
I 've encountered some rather bizzar exception while constructing connection string in my application.Error : An unhandled exception of type 'System.FormatException ' occurred in mscorlib.dllAdditional information : Index ( zero based ) must be greater than or equal to zero and less than the size of the argument list.M...
string basis = `` Data Source= { 0 } ; Initial Catalog= { 1 } ; Persist Security Info= { 2 } ; User ID= { 3 } ; Password= { 4 } '' ; List < string > info1 = new List < string > ( ) { `` SQLSRV '' , `` TEST '' , `` True '' , `` user1 '' , `` pass1 '' } ; string [ ] info2 = new string [ ] { `` SQLSRV '' , `` TEST '' , ``...
Difference between index of List and index of Array
C#
this is my app to excute a threading example , but the output is not as expected , anyone have any clue about that please but the out but is 3__3__3__3__3__3__3__3__3__3__4__4__4__4__4__what happens exactly anyone can explain please thanks
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading ; namespace OTS_Performence_Test_tool { class Program { static void testThread ( string xx ) { int count = 0 ; while ( count < 5 ) { Console.WriteLine ( xx ) ; count++ ; } } static void Main ( string [ ] arg...
multithreading behavior strange C # !
C#
I 'm trying to write a function that takes a function as one of its arguments -- a task I 've done many times before . This works fine : Yet this does n't work : Any idea why the first one works and the second one does n't ?
int RunFunction ( Func < int , int > f , int input ) { return f ( input ) ; } int Double ( int x ) { return x*2 ; } // somewhere else in codeRunFunction ( Double,5 ) ; public static class FunctionyStuff { public static int RunFunction ( this Func < int , int > f , int input ) { return f ( input ) ; } } // somewhere els...
Function of a function works one direction , not the other
C#
I have a library with the following code : In my local copy of Visual Studio 2015 this compiles fine . Last week the build server would let this compile without a problem as well . Suddenly , on Monday the build server started having the error : QueryParser.cs ( 449,53 ) : error CS1620 : Argument 2 must be passed with ...
double result = -1 ; if ( ! string.IsNullOrEmpty ( fieldName ) ) { string value = HttpContext.Current.Request.QueryString [ fieldName ] ; if ( string.IsNullOrEmpty ( value ) ) { value = HttpContext.Current.Request.Form [ fieldName ] ; } if ( string.IsNullOrWhiteSpace ( value ) || ! double.TryParse ( value.Trim ( ) , ou...
Getting `` ref '' keyword required in Double.TryParse
C#
Hallo and thanks for your time.I have recently decided to try using Xamarin.Android , to develop an idea I had.However , I 've run into the weirdest problem I 've ever had.In the above class , when I do a ToString operation on a note object with less than 20 chars in it , I get an unhandled exception . Which I thought ...
public class Note : INote { public string Content { get ; set ; } public DateTime DateTime { get ; set ; } public List < ITag > Tags { get ; set ; } public override string ToString ( ) { try { const int maxLength = 20 ; if ( Content.Length > maxLength ) { return Content.Substring ( 0 , maxLength - 1 ) ; } return Conten...
Unhandled exception in ToString overload
C#
One of my class collects statistics during application execution and I want to store this statistics to disk when application finished . I never destroy this class inside my program so I have tried to store logs to file like that : However I do not see logs I expect to see and also I can not `` catch '' in debugger mom...
~Strategy ( ) { foreach ( var item in statisticItems ) { log.WriteLine ( item.Text ) ; // log is AutoFlush } }
correct way to store information to file when application shutdown
C#
I have a User table that has a BIT NULL column called NxEnabled , and I ca n't change . Some of the records actually contain a NULL in that column.I do n't want to have a Nullable in C # , so it makes sense comparing it to true in the projection ( the code is simplified , but this generates the same error ) : Why does ...
context.Users.Where ( x = > x.Id == 4 ) .Select ( x = > new { Id = x.Id , Name = x.Name , Enabled = x.NxEnabled == true } ) ;
Why is this query throwing an exception ?
C#
Microsoft 's tutorial on events shows how to check an event for null before triggering it : But this leaves open a race-condition , as detailed in Eric Lippert 's blog , where he writes that events should be triggered via a local event to avoid a race-condition : While this works , it has confused many developers who g...
protected virtual void OnChanged ( EventArgs e ) { if ( Changed ! = null ) { // Potential Race-condition at this point ! Changed ( this , e ) ; } } protected virtual void OnChanged ( EventArgs e ) { ChangedEventHandler temp = Changed ; // Local copy of the EventHandler if ( temp ! = null ) { // Race condition avoided b...
Potential downside to triggering an event ?
C#
Let 's say we have an interface likethat is co-variant in T.Then we have another interface and a class implementing it : Now the co-variance allows us to do the followingSo a IEnumerable < SomeClass > is assignable to a variable ( or method parameter ) of type IEnumerable < ISomeInterface > .But if we try this in a gen...
public interface IEnumerable < out T > { /* ... */ } public interface ISomeInterface { } public class SomeClass : ISomeInterface { } IEnumerable < ISomeInterface > e = Enumerable.Empty < SomeClass > ( ) ; public void GenericMethod < T > ( IEnumerable < T > p ) where T : ISomeInterface { IEnumerable < ISomeInterface > e...
Generic constraint ignores co-variance
C#
Say I have been provided a function that looks something like this : I want to use this function but I do n't need the uselessOutput variable at all . How can I get the function to work without using the uselessOutput , preferably without allocating any new memory ?
int doSomething ( int parameter , out someBigMemoryClass uselessOutput ) { ... }
How to neglect/drop a c # `` out '' variable ?
C#
i write code : compile time error : Error 1 Operator '+ ' can not be applied to operands of type 'ConsoleApplication21.MyClass1 ' and 'ConsoleApplication21.MyClass1'So , c # compiler did not like line `` int j = new MyClass1 ( ) + new MyClass1 ( ) ; '' When i open ILDASM , i got same code of operator overloadings : So ...
using System.Runtime.CompilerServices ; namespace ConsoleApplication21 { class Program { static void Main ( string [ ] args ) { int i = new MyClass1 ( ) - new MyClass1 ( ) ; int j = new MyClass1 ( ) + new MyClass1 ( ) ; } } public class MyClass1 { public static int operator - ( MyClass1 i , MyClass1 j ) { return 5 ; } ...
Why C # compiler generate error , even if using Attribute `` SpecialName ''
C#
Given the below console program : When compiled against .Net 4.5.2 using VS 2013 , it will print When compiled against .Net 4.5.2 using VS 2015 , it will print From this question , I kind of understand what is happening , but I 'm confused why there is a change in behavior between versions of VS. From my understanding ...
class Program { private static string _value ; static void Main ( string [ ] args ) { var t = new Action ( ( ) = > _value = `` foo '' ) ; Console.Out.WriteLine ( `` t.Method.IsStatic : { 0 } '' , t.Method.IsStatic ) ; } } t.Method.IsStatic : true t.Method.IsStatic : false
Why is Action.Method.IsStatic different between Visual Studio 2013 and 2015 for certain lambda expressions
C#
I 'm trying to log anything that my application outputs ( including information messages ) into the event log , but the ILogger interface only writes warnings and above there.Here is my program.cs : My appsettings.json : In my application I do the following : In the console output I receive all of the test messages . B...
public static IHostBuilder CreateHostBuilder ( string [ ] args ) = > Host.CreateDefaultBuilder ( args ) .ConfigureLogging ( ( context , logging ) = > { logging.ClearProviders ( ) ; logging.AddConsole ( ) ; logging.AddEventLog ( context.Configuration.GetSection ( `` Logging : EventLog '' ) .Get < EventLogSettings > ( ) ...
ILogger Interface not logging everything into Event Log / Core 3.0
C#
I know the C # System.Collections.Generic.List object is not thread safe . But I am wondering why this piece of code generates null values.This is a part of the list after some seconds : The thread which is responsible to remove the entries from the list can crash , if the entry is not present in the list . Therefore a...
Task.Run ( ( ) = > { for ( var i = 0 ; i < 10 ; i++ ) { var str = $ '' Test { i } '' ; list.Add ( str ) ; if ( i == 9 ) { i = 0 ; } } } ) ; Task.Run ( ( ) = > { while ( true ) { list.Remove ( `` Test 1 '' ) ; list.Remove ( `` Test 2 '' ) ; list.Remove ( `` Test 3 '' ) ; list.Remove ( `` Test 4 '' ) ; list.Remove ( `` T...
null values in List < string > when adding and removing in multiple threads
C#
I work on developing an external API . I added a method to my public interface : It looked good , until one test broke that was passing a null . That made the compiler confused with ambiguous call . I fixed the test with casting the null . However my question is : Should I change the name just because of this ? Or shou...
public void AddMode ( TypeA mode ) ; public void AddMode ( TypeB mode ) ; // the new method , TypeB and TypeA are not related at all TypeA vl = null ; AddMode ( v1 ) ; // this does n't cause a problem
Changing the name just because of Null ?
C#
I am working on a BLE application . I am able to connect to MI band and get the services through my Xamarin forms BLE app . But when I am trying to write characteristics I am getting exception . I 'm getting exceptionCharacteristic does not support write.for the method WriteAsync ( ) . This is my code where I am writin...
private async Task < string > ProcessDeviceInformationService ( IService deviceInfoService ) { try { await adapter.ConnectToDeviceAsync ( device ) ; var sb = new StringBuilder ( `` Getting information from Device Information service : \n '' ) ; var characteristics = await deviceInfoService.GetCharacteristicsAsync ( ) ;...
How to fix GattStatus : 3 - WriteNotPermitted exception for BLE Xamarin forms application ?
C#
I have txt file as follows and would like to split them into double arraysMy goal is to have a series of arrays of each column . i.e . node [ ] = { 0,1,2,3 ) , Axis [ ] = { 0.00 , -83.19 , -56.91 , -42.09 } , ... .I know how to read the txt file and covert strings to double arrays . but the problem is the values are no...
node Strain Axis Strain F P/S Sum Cur Moment0 0.00000 0.00 0.0000 0 0 0 0 0.001 0.00041 -83.19 0.0002 2328 352 0 0 -0.802 0.00045 -56.91 0.0002 2329 352 0 0 1.453 0.00050 -42.09 0.0002 2327 353 0 0 -0.30
Split a string containing various spaces
C#
I want to find all subsets of a given set that are mutually exclusive and contain as many elements of the superset as possible . Where the user defines a meaning for exclusiveness : where at least exclusion ( a , b ) == exclusion ( b , a ) holds.And exclusion ( a , b ) == true is guaranteed if a.Equals ( b ) == trueMy ...
bool exclusion < T > ( T a , T b ) public static HashSet < HashSet < T > > MutuallyExclusive < T > ( this IEnumerable < T > available , Func < T , T , bool > exclusion ) { HashSet < HashSet < T > > finished = new HashSet < HashSet < T > > ( new HashSetEquality < T > ( ) ) ; Recursion < T > ( available , new HashSet < T...
Set of maximal independent subsets via a c # generator
C#
Assume I have this enum defined , where several members have the same underlying value : According to MSDN documentation : If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member 's name based on its underlying value , your code shoul...
enum Number { One = 1 , Eins = 1 , Uno = 1 } var number = Number.One ; Console.WriteLine ( number ) ; Console.WriteLine ( $ '' { Number.One } { Number.Eins } { Number.Uno } '' ) ; Console.WriteLine ( $ '' { nameof ( Number.One ) } { nameof ( Number.Eins ) } { nameof ( Number.Uno ) } '' ) ;
Properly identifying enums with same underlying value
C#
While trying to implement a GetHashCode override similar to Jon 's Skeet 's suggestion in What is the best algorithm for an overridden System.Object.GetHashCode ? I noticed some odd behavior in the order of evaluation that is causing a syntax error when doing a null check on a collection property in the class using the...
public class Foo { public String Name { get ; private set ; } public List < String > Bar { get ; private set ; } public override Int32 GetHashCode ( ) { unchecked { int hash = 17 ; hash = hash * 23 + this.Name == null ? 0 : this.Name.GetHashCode ( ) ; hash = hash * 23 + this.Bar == null ? 0 : this.Bar.GetHashCode ( ) ;...
Why is the order of evaluation different for Collections than for other types using the conditional operator
C#
I have a console app ( c # ) which opens a connection to a sql database , executes a stored procedure and then exits.The stored procedure times itself ( using getdate and datediff ) and returns the timings to the console app.The stored procedure always reports taking about 100 milliseconds to execute.Running the consol...
ExecuteReader when SSMS is not open 300 msExecuteReader when SSMS is not open 300 msExecuteReader when SSMS is not open 300 msOpen SSMS and connect to databaseFirst ExecuteReader when SSMS is open and connected to same database 300 msSecond ExecuteReader with SSMS open and connected 10 ms ! ! ! Third ExecuteReader with...
why is a console app affected by having SSMS open
C#
I have this Json : I have created 2 classes to be used to Deserialize it.But when I try to access the dictionary , I keep getting Unhandled Exception : System.NullReferenceException : Object reference not set to an instance of an object . at `` Console.WriteLine ( jsonTest.Dict.Count ) ; '' Am I Deserializing it wrong ...
{ `` UpdatePack '' : '' updatePacks\/1585654836.pack '' , `` Updates '' : [ { `` Name '' : '' MsgBoxEx '' , `` version '' : '' 1.5.14.88 '' , `` ChangeLog '' : '' BugFix : Form did n't resize correct . `` , `` Hash '' : '' 5FB23ED83693A6D3147A0485CD13288315F77D3D37AAC0697E70B8F8C9AA0BB8 '' } , { `` Name '' : '' Utiliti...
Deserialize Json an access the result
C#
Can I make sure that in dictionary in C # there will be only a single of a specific value in it ? For example , if I define a Dictionary which key is char and value is char , can I make sure that if the character ' a ' is already an existing value , there wo n't be another value ' a ' in the dictionary ? I have a solut...
static void Main ( ) { Dictionary < int , int > dic = new Dictionary < int , int > ( ) ; bool valExists = false ; Console.WriteLine ( `` please enter key and value '' ) ; int key = int.Parse ( Console.ReadLine ( ) ) ; int val = int.Parse ( Console.ReadLine ( ) ) ; foreach ( KeyValuePair < int , int > keyval in dic ) { ...
About Dictionary
C#
When I write Console.WriteLine ( new Point ( 1,1 ) ) ; it does n't call method ToString . But it converts object to Int32 , and write it to console . But why ? It seems as it ignores overridden method ToString .
struct Point { public Int32 x ; public Int32 y ; public Point ( Int32 x1 , Int32 y1 ) { x = x1 ; y = y1 ; } public static Point operator + ( Point p1 , Point p2 ) { return new Point ( p1.x + p2.x , p1.y + p2.y ) ; } public static implicit operator Int32 ( Point p ) { Console.WriteLine ( `` Converted to Int32 '' ) ; ret...
Overriding virtual method in type with conversion method
C#
I have some code that can be called from inside or outside a lock . I need to do stuff when inside the lock . The code itself has no knowledge of where it 's being called from . So , I need something like this : I know it sounds weird and wrong but I need this for compatibility issues . Otherwise I will have to rewrite...
lock ( MyLock ) { if ( INSIDE_LOCK ) ... }
How do I check if current code is `` inside '' lock ?
C#
Recently I came across a proprietary third-party library and there is a method behave in this way : When my code calling this method from main thread , it will block on this method until user clicks , then get the point return from ClickOnDrawMat.However , it does n't block the main thread . I still can press other but...
public Point ClickOnDrawMat ( DrawMat drwmat ) { Point pt ; //waiting user mouse click on DrawMat and assign to pt return pt ; } public void button1_Click ( object sender , EventArgs e ) { Point userClickedPoint = ClickOnDrawMat ( oDrwMat ) ; //Wait until user clicked //Do stuff with point we got } myProgram.frmMain.bu...
Blocking calls but do not block thread
C#
I am trying to build a contact managers program in a console application using a list to store and display the data . I need to view a report that displays a summary of contacts available and then have a menu to allow the user to interact with the program . I have a method to create a contact and a contact object . I a...
static void Main ( string [ ] args ) { //Declare the list List < Contact > contactList = new List < Contact > ( ) ; //Main Driver char menuItem ; Console.WriteLine ( `` Contact List\n '' ) ; menuItem = GetMenuItem ( ) ; while ( menuItem ! = ' Q ' ) { ProcessMenuItem ( menuItem , contactList ) ; menuItem = GetMenuItem (...
remove item selected by the user from a list
C#
out of these which is better and why . or it is just a extra check . not a major difference .
private void NotifyFreeChannelsChanged ( ) //1 . { if ( FreeChannelsChanged ! = null ) { FreeChannelsChanged ( this , null ) ; } } private void NotifyFreeChannelsChanged ( ) //2 . { NotifyCollectionChangedEventHandler h = FreeChannelsChanged ; if ( h ! = null ) h ( this , e ) ; }
Which is the better approach to invoke an event delegate ?
C#
I have the following class hierarchy : I need to be able to invoke any of these methods for a new instance of Child at any given time using reflection however to improve performance I need to resort to Delegate and/or Compiled Expressions.So for example I can have : for which I would need to at runtime invoke these met...
public class Parent { [ DebuggerStepThrough ] public void SayParent ( ) { Console.WriteLine ( `` Parent '' ) ; } } public sealed class Child : Parent { private static int _number = 0 ; public Child ( ) // May contain parameter i.e . not always parameterless consctructor { _number++ ; } [ DebuggerStepThrough ] public vo...
How can I convert C # methods to compiled expressions ?
C#
Long story short , I have this dataGridView and I want the cell [ 0,0 ] to be the cell on the lower-left corner of the grid , not on the top-left of the grid like it does by default.For example , visually , if i do something like : I get this ( sorry not enough reputation to post pictures ) but I 'd like `` a '' to app...
dataGridView1 [ 0 , 0 ] .Value = `` a '' ;
Windows Form : change dataGridView 's first cell origin ?
C#
If I have a method : I am able to call the method by passing in both a DateTime ? and a DateTime . So how does the compiler understand the difference ? Does that mean if I pass in a DateTime Value , the if statement will essentially be soemthing like and all the *.value has been changed to the proper objects ? So all e...
protected int CalculateActualDuration ( DateTime ? startDate , DateTime ? endDate ) { if ( startDate.HasValue & & endDate.HasValue ) { return Math.Abs ( ( int ) ( endDate.Value.Subtract ( startDate.Value ) .TotalMinutes ) ) ; } else { return 0 ; } } if ( true & & true )
How does the compiler understand Nullables ?
C#
Back in time when .NET Reflector was free I used it to gasp into the .NET framework code . It came to my attention that most collections in .NET 2.0 ( I believe this is applicable for current versions too ) use the following mechanism to recognize collection modifications during loops : Now imagine the hypothetical cas...
public class SomeCollection < T > { internal int version = 0 ; // code skipped for brevity public void Add ( T item ) { version++ ; // add item logic ... } public IEnumerator < T > GetEnumerator ( ) { return new SomeCollectionEnumerator < T > ( this ) ; } } public class SomeCollectionEnumerator < T > : IEnumerator < T ...
Modifying a built-in .NET collection int.MaxValue times and more - potential overflow error
C#
I have an asp.net application , which is crashing . There is an entry for this in the windows event logs which contains this callstack : This happens only on a customer machine and I was not able to reproduce it locally . As you see on the top there is an interface ( ILookup , which is really an interface , not a class...
Exception type : EntryPointNotFoundException Exception message : Entry point was not found . at ***.Interfaces.Portal.Repository.ILookup.get_LookupDataCollection ( ) at ***.Portal.Repository.Lookup.GetLookUpValue ( ILookup lookup , Int32 index ) at ***.Portal.Repository.Lookup.GetLookUpValue ( ILookup lookup ) at ***.H...
Is it normal to see an interface in a clr callstack ?
C#
I was reading Improving .NET Application Performance and Scalability . The section titled Avoid Repetitive Field or Property Access contains a guideline : If you use data that is static for the duration of the loop , obtain it before the loop instead of repeatedly accessing a field or property.The following code is giv...
for ( int item = 0 ; item < Customer.Orders.Count ; item++ ) { CalculateTax ( Customer.State , Customer.Zip , Customer.Orders [ item ] ) ; } string state = Customer.State ; string zip = Customer.Zip ; int count = Customers.Orders.Count ; for ( int item = 0 ; item < count ; item++ ) { CalculateTax ( state , zip , Custom...
Compiler optimization of properties that remain static for the duration of a loop
C#
I have a number of classes inheriting from an abstract base class Airplane , examplified : Suppose I want to create another class , AirplaneFactory that takes a list ( in the constructor ) of possible airplanes it can build : How do I limit those types to only Airplane and inherited classes ? The end goal is to create ...
Airplane- > F15- > F16- > Boeing747 class AirplaneFactory { public AirplaneFactory ( List < Type > airplaneTypes ) { ... . } }
Use list of class types ( or similar concept ) to limit valid input
C#
I have this query that i 've been trying to figure out how to convert to LINQ : And here is my LINQ so far : I am getting an error message on the first join stating '' The type of one of the expressions in the join clause is incorrect . Type inference failed in the call to 'Join ' . `` All searches I did , related to t...
select bjbecd , bjbesk , areotx from insku inner join iniwre on bjcomp=a7comp and bjbecd=a7becd and bjbesk=a7besk inner join initem on bjcomp=arcomp and bjbecd=arbecd where a7comp=1 and a7wcde in ( 1,10 ) and a7ohdq > 0 and rtrim ( a7becd ) + rtrim ( a7besk ) not in ( select skucode from eoditems ) ( from i in db.INSKU...
Please help me convert SQL to LINQ
C#
When working on a repository i generaly try to keep the method pretty generic , but this can sometimes lead to calling longer methods , or creating more specificly named methods at the service layer . My question is , how much knowledge of your domain should your a resitory layer have ? For example , I currently have a...
public User GetUniqueByRoleAndRoleProperty < TRole > ( string propertyName , object propertyValue ) { ... } public User GetArtistBySlug ( string slug ) { ... }
How much knowledge of your domain should your repository layer have ?
C#
I have an interface that for example 's sake looks like this : I then have an abstract base class that looks like this : I then inherit from the base class like so : How can I instantiate a MyFoo from a generic method with type parameter FooBase ? I 'm pretty much looking for something like this : The problem I have is...
interface IFoo < TEnum > where TEnum : struct , IConvertible , IComparable , IFormattable { TEnum MyEnum { get ; set ; } } abstract class FooBase < TEnum > : IFoo < TEnum > where TEnum : struct , IConvertible , IFormattable , IComparable { public TEnum MyEnum { get ; set ; } } class MyFoo : FooBase < MyFoo.MyFooEnum > ...
Interface Base class instantiation via generic method
C#
I ran in to the following : I would love to be able to do this . But i think it 's impossible . The compiler ignores the constraints . Why ? ( I know it 's by design ) .I think my 2 options are : Make 2 distinct functions.Make 2 distinct Config classes.Right ?
public void AddConfig < T > ( Config c ) where T : BaseTypeA { // do stuff } public void AddConfig < T > ( Config c ) where T : BaseTypeB { // do stuff }
uniquess of methods and constraints
C#
Is there any way to merge these two constructors into one ? Basically they accept the same array of Point3D type.Thanks .
public Curve ( int degree , params Point3D [ ] points ) { } public Curve ( int degree , IList < Point3D > points ) { }
Merging params and IList < T > constructors
C#
I just found out that you can use var as fieldname.Why is this possible ? Any other keyword as fieldname would not compile .
var var = `` '' ; var string = `` '' ; // error
How is var different than other keywords ?
C#
I 'm trying to access a asp.net variable ( c # ) from JavaScript/jQuery.I 've found a solution , here and here . But unfortunately these are not working for me.Here 's a snippet : Default.aspx.csscript.js_currentUser 's value is always `` < % =CurrentUser % > '' .Any ideas ?
public partial class Default : System.Web.UI.Page { public string CurrentUser { get ; set ; } protected void Page_Load ( object sender , EventArgs e ) { CurrentUser = User.Identity.Name.Split ( '\\ ' ) [ 1 ] ; //I need the value of `` CurrentUser '' } ... } $ ( document ) .ready ( function ( ) { var _currentUser = `` <...
Cant access Variables in JS/jQuery via < % = variable % >
C#
I am working on alpha.dubaiexporters.com.There is a go button clicking on which a search panel appears where I can perform search keyword and category.The issue is that after clicking on go button , search panel appears but if the user does not want to perform any search , he clicks outside anywhere but that search pan...
http : //alpha.dubaiexporters.com/aboutus.aspx < header class= '' header vc_row-fluid vc_col-sm-12 '' > < div class= '' top-header vc_col-sm-12 '' > < div class= '' logo shadows vc_col-sm-3 '' > < a href= '' Default.aspx '' > < img src= '' images/layout/check1.png '' width= '' 230 '' height= '' 69 '' alt= '' Dubai Expo...
How to close a div by clicking outside anywhere ?
C#
So I do n't have an in-depth knowledge of how data is stored in the .NET Framework in terms of custom types , but I was looking for an explanation on how the casting system is working.For example , if one were to do an explicit cast from a ValueType Struct like Char into Byte as follows : I would be told that B is a By...
char C = ' # ' ; byte B = ( byte ) C ; Console.WriteLine ( B.GetType ( ) ) ; // Outputs `` Byte '' class Plant { } class Flower : Plant { } Flower Rose = new Flower ( ) ; Plant RoseBush = ( Plant ) Rose ; Console.WriteLine ( RoseBush.GetType ( ) ) ; //Outputs FlowerPlant Rose = new Flower ( ) ; Plant RoseBush = ( Plant...
Casting Causes Different GetTypes