lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
There probably is a question on this already , but I was n't able to come up with the search terms to find an answer..I 'm probably missing something obvious here , but why am I not allowed to do the following , which gives the error : `` Argument 1 : can not convert from System.Collections.Generic.IEnumerable < TType ...
public interface A { void Foo ( ) ; } public class B : A { public void Foo ( ) { } } class Test < TType > where TType : A { public Test ( IEnumerable < TType > testTypes ) { DoSomething ( testTypes ) ; } void DoSomething ( IEnumerable < A > someAs ) { } } class Test { public Test ( IEnumerable < B > testTypes ) { DoSom...
Constraint on generic type can not be used in IEnumerable ?
C#
I 've been reading a lot about why constructors are useful and all the resources I found specify that constructors are used to initialize the instances of your classes . A key benefit of using a constructor is that it guarantees that the object will go through proper initialization before being used , often accepting p...
public Car ( int speedCurrent , int gearCurrent ) { speed = speedCurrent ; gear= startGear ; } Car myCar = new Car ( 0 , 0 ) ; public int speed { get ; set ; } public int gear { get ; set ; } Car myCar = new Car ( ) ; myCar.speed = 0 ; myCar.gear = 0 ;
Constructors in C #
C#
I am iterating over elements which were taken from HTML . structureElement seems to hold found element , but when I run .FindElement ( ) on it , it returns always value from first iteration . Why is that ? Here is my code :
IReadOnlyCollection < IWebElement > structureElements = driver.FindElements ( By.XPath ( `` .//div [ contains ( @ id , 'PSBTree_x-auto- ' ) ] '' ) ) ; //.Where ( sE = > sE.FindElement ( By.XPath ( `` //img [ @ title ] '' ) ) .GetAttribute ( `` title '' ) ! = `` Customer Item '' ) IWebElement tmp ; foreach ( IWebElement...
FindElement doesnt iterate when iterating elements in IReadOnlyCollection
C#
How do I declare and use generic interfaces ( see namespace Sample2 ) to work in the same way as with classes in namespace Sample1 ? I know there is a workaround ( see namespace Sample2Modified ) but that is not what I 'm trying to achieve.Works with classesWhen using classes , this works fine : Does not work with inte...
namespace Sample1 { public class ClassContainer < T1 , T2 > where T1 : T2 { } public class ClassParent { } public class ClassChild : ClassParent { } public class ClassSampleDoesWork < TItem > where TItem : ClassParent { ClassContainer < IEnumerable < TItem > , IEnumerable < ClassParent > > SomeProperty { get ; set ; } ...
How to use a generic type parameter as type parameter for a property declared as an interface with type constraints ?
C#
I 'm a relative newbie to C # , although I am a competent programmer , and I confess that I am totally confused as to whether or not it is a good idea to write custom collection classes . So many people seem to say `` do n't '' , yet there is a whole set of base classes for it in C # .Here is my specific case . I have ...
public class Service { public RouteLinks RL ; // A collection of RouteLink types ... } public class RouteLink { public string FirstStopRef ; public string LastStopRef ; public Tracks RouteTrack ; // Another collection , this time of Track types }
C # Collection classes - yes or no
C#
I am using the new JsonSerializer from NETCore 3.0 's System.Text.Json namespace to deserialize Json documents like this : Response is defined as : The fact that JsonDocument implements IDisposable makes me wonder if by keeping a reference to an element ( Bar ) that can be contained in a JsonDocument , will create memo...
var result = JsonSerializer.Deserialize < Response > ( json , options ) ; public class Response { public string Foo { get ; set ; } public JsonElement Bar { get ; set ; } }
Am I creating a leak here ?
C#
I just lifted this snippet from a website and it proved to be exactly the solution I needed for my particular problem . I have no idea what it is ( particularly the delegate and return parts ) and the source does n't explain it . Hoping SO can enlighten me .
myList.Sort ( delegate ( KeyValuePair < String , Int32 > x , KeyValuePair < String , Int32 > y ) { return x.Value.CompareTo ( y.Value ) ; } ) ;
ok , this worked . what is it exactly ?
C#
In C # ( .NET 4.5 ) I would like to subscribe to an event while I 'm creating an object.The following , of course , would work : But want to find out if it 's possible to do something along the lines of : Post-discussion edit : This is in order to accomplish is something like :
CheckBox c = new CheckBox ( ) ; c.Name = `` TheCheckBox '' ; c.Checked += c_Checked ; CheckBox c = new CheckBox ( ) { Name = `` TheCheckBox '' , Checked += c_Checked } MyUniformGrid.Add ( new CheckBox ( ) { Name = `` TheCheckBox '' , Checked += CheckHandler } ) ;
Subscribing to event while creating object in C #
C#
Given an Enumerable , I want to Take ( ) all of the elements up to and including a terminator ( throwing an exception if the terminator is not found ) . Something like : ..except not crappy . Only want to walk it once.Is this concisely possible with current operators in .NET 4 and Rx or do I need to write a new operato...
list.TakeWhile ( v = > ! condition ( v ) ) .Concat ( list.Single ( condition ) ) public static IEnumerable < T > TakeThroughTerminator < T > ( [ NotNull ] this IEnumerable < T > @ this , Func < T , bool > isTerminatorTester ) { foreach ( var item in @ this ) { yield return item ; if ( isTerminatorTester ( item ) ) { yi...
Looking for a particular Enumerable operator sequence : TakeWhile ( ! ) + Concat Single
C#
I did this pattern to match nested divs : This works nicely , as you can see in regex101.However , when I write the code below in C # : It throws me an error : As you can see \g does n't work in c # . How can I match the first subpattern then ?
( < div [ ^ > ] * > ( ? : \g < 1 > | . ) * ? < \/div > ) Regex findDivs = new Regex ( `` ( < div [ ^ > ] * > ( ? : \\g < 1 > | . ) * ? < \\/div > ) '' , RegexOptions.Singleline ) ; Additional information : parsing `` ( < div [ ^ > ] * > ( ? : \g < 1 > | . ) * ? < \/div > ) '' - Unrecognized escape sequence \g .
How can I match the first subpattern in C # ?
C#
There are type parameters for methods . Why there are no type parameters for constructors ? ExampleI think there are several ( not many ) examples where it would be usefull . My current problem was following : A Delegate is enough for my class . But to pass it as method group I need to define the parameter as a Func < ...
internal class ClassA { private readonly Delegate _delegate ; public ClassA < T > ( Func < T > func ) { _delegate = func ; } }
Why are type parameters not allowed in constructors ?
C#
This question is probably language-agnostic , but I 'll focus on the specified languages.While working with some legacy code , I often saw examples of the functions , which ( to my mind , obviously ) are doing too much work inside them . I 'm talking not about 5000 LoC monsters , but about functions , which implement p...
void WorriedFunction ( ... ) { // Of course , this is a bit exaggerated , but I guess this helps // to understand the idea . if ( argument1 ! = null ) return ; if ( argument2 + argument3 < 0 ) return ; if ( stateManager.currentlyDrawing ( ) ) return ; // Actual function implementation starts here . // do_what_the_funct...
General function question ( C++ / Java / C # )
C#
I want a regex pattern to find any integer in the string , but not float ( with decimal point as `` . '' or `` , '' . So for string : abc111.222dfg333hfg44.55it should only find:333I created regex pattern : but it fails when using in C++ STL regex . It throws exception : but it works nice in C # Regex classUPDATE : My ...
( ? < ! \\d [ \\. , ] |\\d ) \\d+ ( ? ! [ \\. , ] \\d+|\\d ) Unhandled exception at at 0x76AF4598 in xxxxxx.exe : Microsoft C++ exception : std : :regex_error at memory location 0x00C1F218 . smatch intMatch ; regex e1 ( `` ( ? < ! \\d [ \\. , ] |\\d ) \\d+ ( ? ! [ \\. , ] \\d+|\\d ) '' ) ; string s ( `` 111.222dfg333hf...
regex : find integer but not float
C#
I am working on a multi-touch app using Monogame , where multiple users can work on a larger multi-touch screen with separate documents/images/videos simultaneously , and I was wondering if it 's possible to make gestures `` context-aware '' , i.e . two fingers pinching a document on one side of the wall should n't aff...
if ( TouchPanel.IsGestureAvailable ) { var gesture = TouchPanel.ReadGesture ( ) ; // do stuff }
Is it possible to get `` contextual '' gestures in Monogame/XNA ?
C#
I just do n't get something in the .NET generic type casting.Can someone explain what happens in the following code snippet ?
void Main ( ) { IEnumerable < int > ints = new List < int > ( ) ; IEnumerable < string > strings = new List < string > ( ) ; var rez1= ( IEnumerable < object > ) ints ; //runtime error var rez2= ( IEnumerable < object > ) strings ; //works var rez3= ( List < object > ) strings ; //runtime error }
Generics type casting
C#
Can someone explain to me why the below code outputs what it does ? Why is T a String in the first one , not an Int32 , and why is it the opposite case in the next output ? This puzzle is from an interview with Eric LippertWhen I look through the code , I really have no idea if it 's going to be an Int32 or a String :
public class A < T > { public class B : A < int > { public void M ( ) { System.Console.WriteLine ( typeof ( T ) ) ; } public class C : B { } } } public class P { public static void Main ( ) { ( new A < string > .B ( ) ) .M ( ) ; //Outputs System.String ( new A < string > .B.C ( ) ) .M ( ) ; //Outputs System.Int32 Conso...
Puzzle from an Interview with Eric Lippert : Inheritance and Generic Type Setting
C#
I have a List < string > myList in my class that I want to be readonly for the class users.Like this I thought I could set the myList value inside my class in my private members and make it readonly for the class users . But I realised that declaring it that way I 'm unable to set any value .
List < strign > myList { get ; } private void SetListValue ( ) { myList = new List < string > ( ) ; myList.Add ( `` ss '' ) ; }
How to make a readonly C # List by non declaring its set attribute
C#
I have a Flags Enum : and then a classAssuming the following values and a specific range period : How can substract from the totalSeconds the task 's totalSeconds ? So basically I want to exclude from the totalSeconds the period when the task occures which is every Monday , Tuesday , Wednesday between 00:00 and 06:00 w...
[ Flags ] public enum WeekDays { Monday = 1 , Tuesday = 2 , Wednesday = 4 , Thursday = 8 , Friday = 16 , Saturday = 32 , Sunday = 64 } public class Task { public Task ( ) { } public int Days { get ; set ; } public TimeSpan Start { get ; set ; } public TimeSpan End { get ; set ; } } Task task = new Task ( ) ; task.Days ...
c # DateTime range exclude specific ranges
C#
I 'm allowing users to input their own SQL statement to execute , but only if it 's a SELECT statement . Is there a way to detect if the SQL statement is anything but this , i.e . an ALTER , INSERT , DROP , etc. ? I 'll worry about other concerns such as a query locking up a table and such later , but this is more of a...
public void ExecuteQuery ( string connectionString , int id ) { //The SQL statement will be user input var sql = `` SELECT ColumnA , ColumnB , ColumnC FROM MyTable where MyTableId = @ Id '' ; var split = sql.Split ( ' ' ) ; if ( split [ 0 ] .ToUpper ( ) ! = `` SELECT '' ) Console.WriteLine ( `` Only use a SELECT statem...
Prevent Non-SELECT SQL Statements
C#
Is it possible to add dates in C # ? I tried this but it does n't work .
( DateTime.Today.ToLongDateString ( ) + 10 )
Adding DateTime in C #
C#
I have a WPF program , and when I localize it , it fails . I created this XML namespace , which corresponds to the file location , in the Window element : This is how I am localizing each element : The designer works perfectly fine , and I when I choose Resources. , auto-complete pulls up the available items , but when...
xmlns : properties= '' clr-namespace : ResxEditor.Properties '' < Button Content= '' { x : Static properties : Resources.FilePickerButton_AddFile } '' / >
Why ca n't I localize my WPF program ? I get `` Exception thrown : 'System.Windows.Markup.XamlParseException ' in PresentationFramework.dll ''
C#
I recently started learning c # and learned that there are 2 ways to have my code output even numbers when I write this For loop . I learned the syntax of version 2 , which is intuitive to me . However , version 1 was an exampled I found elsewhere online . I want to understand if there is a difference between the two v...
//Version 1for ( int num = 0 ; num < 100 ; num+=2 ) { Console.WriteLine ( num ) ; } //Version 2for ( int num = 0 ; num < 100 ; num++ ) { if ( num % 2 == 0 ) { Console.WriteLine ( num ) ; } }
What is the more efficient syntax to produce an even number in my console project ?
C#
While perusing Twitter I spotted a tweet by a Game Developer I follow that just said ; @ ChevyRay 2:44 AM - 5 Jul 2016 i give you : the stupidest 8 lines of code i ’ ve ever written that is actually used by my game ’ s code Immediately I looked at it and thought to myself what does this do ? I 'm sure the post was mean...
static IEnumerable < int > RightAndleft { get { yield return 1 ; yield return -1 ; } }
What is the purpose of Yield and how does it work ?
C#
I 'm creating a query string in a web form , and I 'm dealing with values from the parameters that might be null . There are lots of ways to check and fix these , but the most elegant one I found is the following : The only issue is ... it does n't work . When the code reaches this part , the string stops assigning val...
string pass ; pass = `` BillabilityDetail.aspx ? _startDate= '' + _startDate.Text + `` & _endDate= '' + _endDate.Text + `` & _isContractor= '' + _isContractor.SelectedValue + `` & _busUnit= '' + _busUnit.Text + `` & _projectUnit= '' + _projectUnit.SelectedValue + `` & _leadCon= '' + _leadCon.Value ? ? -1 + `` & _acctEx...
Why is the null coalescing operator breaking my string assignment in c # ?
C#
What is the difference betweenandThey seem to give me the same results .
var q_nojoin = from o in one from t in two where o.SomeProperty == t.SomeProperty select new { o , t } ; var q_join = from o in one join t in two on o.SomeProperty equals t.SomeProperty select new { o , t } ;
What is the difference between where and join ?
C#
I 'm trying the PagedList.Mvc library from herehttps : //github.com/TroyGoode/PagedListwhich has this usage sampletypical implmentations of MyProductDataSource.FindAllProducts ( ) ; are along the lines ofwhich of course has the InvalidOperationException ( ) and DBContext is already disposed messageLooking for best prac...
var products = MyProductDataSource.FindAllProducts ( ) ; //returns IQueryable < Product > representing an unknown number of products . a thousand maybe ? var pageNumber = page ? ? 1 ; // if no page was specified in the querystring , default to the first page ( 1 ) var onePageOfProducts = products.ToPagedList ( pageNumb...
How to return IQueryable < T > for further querying
C#
My questions as follows , I need to check conditions through the database . which means in the simple application we check if conditions like this.Suppose , Client , needs to change the condition dynamically , which means he need to add additional condition to the system like , if 31 < = age & & age < = 40 = > Range 31...
private static void Main ( string [ ] args ) { Console.WriteLine ( `` Enter your age '' ) ; var age = int.Parse ( Console.ReadLine ( ) ? ? throw new InvalidOperationException ( ) ) ; if ( 5 < = age & & age < = 10 ) { Console.WriteLine ( `` Range 5 - 10 '' ) ; } else if ( 11 < = age & & age < = 20 ) { Console.WriteLine ...
How to check if statements dynamically
C#
Newtonsoft.Json.Linq.JObject implemented IEnumerable < T > , and not explicit implementation , but why ca n't do this : WHY ? Thanks .
using System.Linq ; ... var jobj = new JObject ( ) ; var xxx = jobj.Select ( x = > x ) ; //errorforeach ( var x in jobj ) { } //no error
Why ca n't use LINQ methods on JObject ?
C#
I 've got code in a button click like so : Nowhere else but in the finally block is the cursor set back to default , yet it does `` get tired '' and revert to its default state for some reason . Why would this be , and how can I assure that it will not stop `` waiting '' until the big daddy of all the processes ( Gener...
try { Cursor = Cursors.WaitCursor ; GenerateReports ( ) ; } finally { Cursor = Cursors.Default ; GC.Collect ( ) ; GenPacketBtn.Enabled = true ; }
Why would the hourglass ( WaitCursor ) stop spinning ?
C#
I write simple library wich returns List of names.But , what i should returns if i can not find anything ? or example : This code can be used from another components and i do not want to corrupted it.If i return null- i think it is right way to check it . But , may be i should return empty list ? Thank you .
return new List < String > ( ) ; return null ; var resultColl=FindNames ( ... ) ;
What result i should return ?
C#
I have the following class : In English grammar you can ’ t have “ is something equal to something ” or “ does something greater than something ” so I don ’ t want Is.EqualTo and Does.GreaterThan to be possible . Is there any way to restrict it ? Thank you !
public class Fluently { public Fluently Is ( string lhs ) { return this ; } public Fluently Does ( string lhs ) { return this ; } public Fluently EqualTo ( string rhs ) { return this ; } public Fluently LessThan ( string rhs ) { return this ; } public Fluently GreaterThan ( string rhs ) { return this ; } } var f = new ...
Question regarding fluent interface in C #
C#
I would like to print products in order of quantity.The product with a bigger total should be first.What am I missing here as it 's NOT printing in order or total
class Program { static void Main ( ) { var products=new List < Product > { new Product { Name = `` Apple '' , Total = 5 } , new Product { Name = `` Pear '' , Total = 10 } } ; var productsByGreatestQuantity = products.OrderBy ( x = > x.Total ) ; foreach ( var product in productsByGreatestQuantity ) { System.Console.Writ...
How do you order by Greatest number in linq
C#
I am cross-posting this question from Microsoft Community because I have n't gotten any response there , and maybe someone here can shed some light on this.I have noticed an issue that is specific to Word 2013 when using VSTO to process a document.The document contains an image in the header or footer that has its Layo...
The remote procedure call failed . ( Exception from HRESULT : 0x800706BE ) private static bool ShapesWithinGroup ( Shape shape ) { var result = false ; try { // shape.GroupItems throws the exception if ( shape.GroupItems ! = null & & shape.GroupItems.Count > 0 ) { result = true ; } } catch ( UnauthorizedAccessException...
BUG : Word 2013 VSTO Can not Handle Image in Header Formatted Behind or In Front of Text
C#
I want to replace every occurrence of one of those magic 2-byte packages in my List < byte > with a single byte : { 0xF8 , 0x00 } - > Replace with 0xF8 { 0xF8 , 0x01 } - > Replace with 0xFB { 0xF8 , 0x02 } - > Replace with 0xFD { 0xF8 , 0x03 } - > Replace with 0xFEFor example : This is my solution so far , which works ...
List < byte > message = new List < byte > { 0xFF , 0xFF , 0xFB , 0xF8 , 0x00 , 0xF8 , 0x01 , 0xF8 , 0x02 , 0xF8 , 0x03 , 0xFE } ; // will be converted to : List < byte > expected = new List < byte > { 0xFF , 0xFF , 0xFB , 0xF8 , 0xFB , 0xFD , 0xFE , 0xFE } ; public static void RemoveEscapeSequences ( List < byte > mess...
Replace two bytes in a generic list
C#
I have a C # application that uses an unmanaged C++ DLL . I 've found a crash that only happens in WinXP ( not Win7 ) when the memory I 'm passing back from the C++ DLL is too big.The basic flow is that C # starts an operation in the C++ DLL by calling a start function , in which it provides a callback . The C++ DLL th...
typedef void ( CALLBACK *onfilecallbackfunc_t ) ( LPCWSTR ) ; DLL_API void NWAperture_SetOnFileCallback ( onfilecallbackfunc_t p_pCallback ) ; l_pFileCallback ( _wstringCapture.c_str ( ) ) ; public delegate void FileCallback ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string buffer ) ; public static extern void SetOnFileC...
What 's the memory limit in WinXP when getting a callback from a C++ DLL in C # ?
C#
The issue is that VS2010 Code Analysis is returning two CA2000 warnings for a particular function . I have n't been successful at reproducing the warnings with a smaller block of code , so I 've posted the original function in it 's entirety.The two CA2000 warnings pertain to the using statements containing the SqlConn...
public int SaveTransaction ( Transaction tx , UserAccount account ) { if ( tx == null ) { throw new ArgumentNullException ( `` tx '' ) ; } if ( account == null ) { throw new ArgumentNullException ( `` account '' ) ; } bool isRefund = tx.TransactionType == LevelUpTransaction.TransactionTypes.Refund ; int pnRef = 0 ; usi...
CA2000 Warning That Can Be Removed By Commenting out Seemingly Unrelated Code
C#
Do I have to wrap all my IDisposable objects in using ( ) { } statements , even if I 'm just passing one to another ? For example , in the following method : Could I consolidate this to just one using like this : Can I count on both the Stream and the StreamReader being disposed ? Or do I have to use two using statemen...
public static string ReadResponse ( HttpWebResponse response ) { string resp = null ; using ( Stream responseStream = response.GetResponseStream ( ) ) { using ( StreamReader responseReader = new StreamReader ( responseStream ) ) { resp = responseReader.ReadToEnd ( ) ; } } return resp ; } public static string ReadRespon...
Is it necessary to nest usings with IDisposable objects ?
C#
I 'm trying to create a Dynamic Data website which should allow an administrator to directly edit the data in most tables in a database.So far , I have an EDMX and POCO classes , all attached to an Interface used to apply the DataAnnotations on the fields.I want to have an editable grid for each table , so I edited the...
[ MetadataType ( typeof ( ILINK_ENTITES_MODELISEES_MetaData ) ) ] public partial class LINK_ENTITES_MODELISEES : ILINK_ENTITES_MODELISEES_MetaData { public int id_entite_modelisee { get ; set ; } public short id_entite { get ; set ; } public short id_lob { get ; set ; } public System.DateTime date_val_debut { get ; set...
`` The ORDER BY sort key ( s ) type must be order-comparable '' with dynamic data
C#
I have this code that emits some IL instructions that calls string.IndexOf on a null object : This is the generated IL code : As you can see there are three nop instructions before the call instruction.First I thought about Debug/Release build but this is not compiler generated code , I am emitting raw IL code and expe...
MethodBuilder methodBuilder = typeBuilder.DefineMethod ( `` Foo '' , MethodAttributes.Public , typeof ( void ) , Array.Empty < Type > ( ) ) ; var methodInfo = typeof ( string ) .GetMethod ( `` IndexOf '' , new [ ] { typeof ( char ) } ) ; ILGenerator ilGenerator = methodBuilder.GetILGenerator ( ) ; ilGenerator.Emit ( Op...
Why is IL.Emit method adding additional nop instructions ?
C#
Consider a class like this : How do I make the following code work ? Now I get this exception : InvalidCastException : Unable to cast object of type 'MyString ' to type 'System.String ' .
public class MyString { private string _string ; public string String { get { return _string ; } set { _string = value ; } } public MyString ( string s ) { _string = s ; } public static implicit operator string ( MyString str ) { return str.String ; } public static implicit operator MyString ( string str ) { return new...
String cast not working
C#
This is weird ... done updates loads of times before but can not spot why this is different.although I am using .net 4.0 now - however i doubt its a bug in its L2S implementation . Its not like this is a wierd and wonderful application of it . Although i am fairly sure this code worked whilst i was using the RC.I have ...
public partial class Client : ICopyToMe < Client > public interface ICopyToMe < T > { void CopyToMe ( T theObject ) ; } public override int GetHashCode ( ) { int retVal = 13 ^ ID ^ name.GetHashCode ( ) ; return retVal ; } public override bool Equals ( object obj ) { bool retVal = false ; Client c = obj as Client ; if (...
Linq2Sql - attempting to update but the Set statement in sql is empty
C#
I 'm working with a MongoDB database . I know when you insert a DateTime into Mongo , it converts it to UTC . But I 'm making a unit test , and my Assert is failing.I must be missing something obvious . When I look in the debugger , I can see that the datetime 's match , but the assert still says they do not ( but they...
[ TestMethod ] public void MongoDateConversion ( ) { DateTime beforeInsert = DateTime.Now ; DateTime afterInsert ; Car entity = new Car { Name = `` Putt putt '' , LastTimestamp = beforeInsert } ; // insert 'entity ' // update 'entity ' from the database afterInsert = entity.LastTimestamp.ToLocalTime ( ) ; Assert.AreEqu...
DateTime ToLocalTime failing
C#
I asked a question and got answered here about performance issues which I had a with a large collection of data . ( created with linq ) ok , let 's leave it aside.But one of the interesting ( and geniusly ) optimization - suggested by Marc - was to Batchify the linq query . Here , the purpose of Batchify is to ensure t...
/*1*/ static IEnumerable < T > Batchify < T > ( this IEnumerable < T > source , int count ) /*2*/ { /*3*/ var list = new List < T > ( count ) ; /*4*/ foreach ( var item in source ) /*5*/ { /*6*/ list.Add ( item ) ; /*7*/ if ( list.Count == count ) /*8*/ { /*9*/ foreach ( var x in list ) yield return x ; /*10*/ list.Cle...
Batchify long Linq operations ?
C#
I was excited to create my first app with C # 5.0 , and I wanted to use the async/await keywords to ease the pains of async data calls.I 'm a bit baffled that interfaces does not allow the async keyword to be part of the contract , as the await keyword only works for async marked methods . This would mean that it is im...
IAsyncRepository < T > { Task < IList < T > > GetAsync ( ) ; // no 'async ' allowed } abstract class AsyncRepositoryBase < T > { public abstract Task < IList < T > > GetAsync ( ) ; // no 'async ' allowed IAsyncRepository < Model > repo = ioc.Resolve < IAsyncRepository < Model > > ( ) ; var items = await repo.GetAsync (...
Does the lack of the async keyword in interfaces break DI in C # 5.0 ?
C#
Let 's say that I have a class ( ClassA ) containing one method which calls the constructor of another class , like this : The class ClassB looks like this : ... and ClassC is even more simple : If I put these classes in their own assembly and compile the whole solution I do n't get any errors . But if I replace the us...
public class ClassA { public void CallClassBConstructor ( ) { using ( ClassB myB = new ClassB ( ) ) { ... } } } public class ClassB : IDisposable { public ClassB ( ) { } public ClassB ( string myString ) { } public ClassB ( ClassC myC ) { } public void Dispose ( ) { ... } } public class ClassC { } using ( ClassB myB = ...
Why am I forced to reference types in unused constructors ?
C#
I have an instance variable with several members , many of which have their own members and so on . Using the debugger and watch variables , I found a string variable with a specific value that I need by diving into this variable 's members.However , after spending some time on other things and coming back to this , I ...
myVariable|| -- aMember1| | -- subMember = `` A value '' || -- aMember2 | -- subMember = `` Another value ''
Find a variable with a given value in VS2008
C#
For the following code : The result is B.G ( ) , whereas the result of similar C++ code would be D.G ( ) .Why is there this difference ?
class B { public String G ( ) { return `` B.G ( ) '' ; } } class D : B { public String G ( ) { return `` D.G ( ) '' ; } } class TestCompile { private static String TestG < T > ( T b ) where T : B { return b.G ( ) ; } static void Main ( string [ ] args ) { TestG ( new D ( ) ) ; } }
Why does this generic method call the base class method , not the derived class method ?
C#
For example , is there anything wrong with something like this ? If it were just a simple integer variable declaration it would be fine because once it went out of scope and would later be collected by the garbage collector but events are a bit .. longer-living ? Do I have to manually unsubscribe or take any sort of me...
private void button1_Click ( object sender , EventArgs e ) { Packet packet = new Packet ( ) ; packet.DataNotSent += packet_DataNotSent ; packet.Send ( ) ; } private void packet_DataNotSent ( object sender , EventArgs e ) { Console.WriteLine ( `` Packet was n't sent . `` ) ; } class Packet { public event EventHandler Da...
Anything wrong with short-lived event handlers ?
C#
I have a map-tile setting I 'm updating through a menu-button . I 've got an odd situation where I was only hitting an error on release builds . Code is as follows : View-ModelViewThis was all working fine in my developer environment but when I generated a release build I was getting the following : ErrorSystem.Invalid...
private KnownTileSource _selectedTile ; public KnownTileSource SelectedTile { get { return _selectedTile ; } private set { _selectedTile = value ; ... OnPropertyChanged ( `` SelectedTile '' ) ; } } < Window ... xmlns : predefined= '' clr-namespace : BruTile.Predefined ; assembly=BruTile '' > ... < MenuItem Header= '' _...
Private setter throwing error only on release build
C#
I need to make my mutable class immutable , now it looks like as following . However , still I 'm not sure that I have a fully `` immutable* class , and if it is , what kind of immutability this is called ? Based on my application B needs to be changed from time to time ; hence to keep the property of immutability , ev...
public class B < C , M > where C : IComparable < C > where M : IMetaData { internal B ( char tau , M metadata , B < C , M > nextBlock ) { if ( tau == ' R ' ) omega = 1 ; _lambda = new List < Lambda < C , M > > ( ) ; _lambda.Add ( new Lambda < C , M > ( tau : tau , atI : metadata ) ) ; foreach ( var item in nextBlock.la...
Can I call this C # class `` immutable '' ?
C#
What I am trying to do is load in objects from an XML save file . The problem is those objects are configurable by the user at runtime , meaning i had to use reflection to get the names and attributes of those objects stored in an XML file.I am in the middle of a recursive loop through the XML and up to the part where ...
private void LoadMenuData ( XmlNode menuDataNode ) { foreach ( object menuDataObject in m_MenuDataTypes ) { Type menuDataObjectType = menuDataObject.GetType ( ) ; if ( menuDataObjectType.Name == menuDataNode.Name ) { //create object } } }
Generically creating objects in C #
C#
I am running the following program on two different machines : On one machine , with .NET 4.5 and Visual Studio 2012 installed this prints `` true '' , on another one , with .NET Framework 4.6.2 and Visual Studio 2015 it prints `` false '' .I thought that anonymous methods were static if they are defined in a static co...
static class Program { static void Main ( string [ ] args ) { Func < int > lambda = ( ) = > 5 ; Console.WriteLine ( lambda.GetMethodInfo ( ) .IsStatic ) ; Console.ReadLine ( ) ; } }
Anonymous method in static class is non-static ? How to invoke it ?
C#
I want to convert a DateTime ? to string . If a date is null then return `` '' , else return a string format like this : `` 2020-03-05T07:52:59.665Z '' . The code is something like this but it wo n't work . It said `` DateTime ? '' do not contain a definition for `` ToUniversalTime '' . Someone know how to fix this ?
DateTime ? date = DateTime.UtcNow ; var dateInUTCString = date == null ? `` '' : date.ToUniversalTime ( ) .ToString ( `` yyyy'-'MM'-'dd'T'HH ' : 'mm ' : 'ss ' . 'fff ' Z ' '' ) ;
Convert DateTime ? to string
C#
Just for fun I built a quicksort implementation in C # with Linq : It sorts 10000 random integers in about 13 seconds.Changing it to use int [ ] instead of List results in about 700 times better performance ! It only takes 21ms to sort the same 10000 random integers . Just looking at the code I would have assumed this ...
public static IEnumerable < T > quicksort < T > ( IEnumerable < T > input ) where T : IComparable < T > { if ( input.Count ( ) < = 1 ) return input ; var pivot = input.FirstOrDefault ( ) ; var lesser = quicksort ( input.Skip ( 1 ) .Where ( i = > i.CompareTo ( pivot ) < = 0 ) ) ; var greater = quicksort ( input.Where ( ...
Quicksort with Linq performance Advantage passing T [ ] vs. IEnumerable < T >
C#
We have several modules in our software that ship as a single product . When a module is activated , those features become available . We would like our OData APIs to follow the same pattern . However I ca n't figure out how to make the $ metadata ignore controllers for modules that have been disabled . Basically I wan...
static public void Register ( HttpConfiguration config ) { config.MapHttpAttributeRoutes ( ) ; var builder = new ODataConventionModelBuilder ( ) ; builder.EntitySet < Module1Entity > ( `` Module1Entities '' ) ; builder.EntitySet < Module2Entity > ( `` Module2Entities '' ) ; config.MapODataServiceRoute ( `` odata '' , `...
Disabling OData V4 meta data and controllers at runtime
C#
The following short but complete example programwith T replaced by the following typesyields the following interesting results on my machine ( Windows 7 .NET 4.5 32-bit ) Question 1 : Why is ComplexClass so much slower than SimpleClass ? The elapsed time seems to increase linearly with the number of fields in the class...
const long iterations = 1000000000 ; T [ ] array = new T [ 1 < < 20 ] ; for ( int i = 0 ; i < array.Length ; i++ ) { array [ i ] = new T ( ) ; } Stopwatch sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < iterations ; i++ ) { array [ i % array.Length ] .Value0 = i ; } Console.WriteLine ( `` { 0 , -15 } { 1 } { 2 : n0...
Field access through array is slower for types with more fields
C#
I 'm working with an external library that has an enum . There are some members of this enum that , when you call ToString ( ) on them , return the name of a different member of the enum.I know that when two enum members have the same numerical value , you can get behavior like this , but I know , from decompilation an...
Console.WriteLine ( `` TOKEN_RIGHT = { 0 } '' , Tokens.TOKEN_RIGHT.ToString ( ) ) ; //prints TOKEN_OUTERConsole.WriteLine ( `` TOKEN_FROM = { 0 } '' , Tokens.TOKEN_FROM.ToString ( ) ) ; //prints TOKEN_FROMConsole.WriteLine ( `` TOKEN_OUTER = { 0 } '' , Tokens.TOKEN_OUTER.ToString ( ) ) ; //prints TOKEN_FULL public enum...
Why does Enum.ToString ( ) not return the correct enum name ?
C#
Let 's say I have an interface like that : Is there any way to implement the DoSomething method with type constraint ? Obviously , this wo n't work : This obviously wo n't work because this DoSomething ( ) wo n't fully satisfy the contract of IAwesome - it only work for a subset of all possible values of the type param...
interface IAwesome { T DoSomething < T > ( ) ; } class IncrediblyAwesome < T > : IAwesome where T : PonyFactoryFactoryFacade { public T DoSomething ( ) { throw new NotImplementedException ( ) ; } }
Type constraints on implementations of generic members of non-generic interfaces in C #
C#
I 'm working on project in which I 'm Posting data from asp.net webform to WCF service . I 'm posting data through params and the service respond me back a JSON string . Now I have an issue in deserialize . I read many threads but did n't find any solution . Hope someone can sort out my problem . Thanks in AdvanceRespo...
string URL = `` http : //localhost:32319/ServiceEmployeeLogin.svc '' ; WebRequest wrGETURL ; wrGETURL = WebRequest.Create ( URL+ '' / '' +emp_username+ '' / '' +emp_password+ '' / '' +emp_type ) ; wrGETURL.Method = `` POST '' ; wrGETURL.ContentType = @ '' application/json ; charset=utf-8 '' ; HttpWebResponse webrespons...
How to Deserialize JSON
C#
I found with or without flags attributes , I can do bit operation if I defined the following enumI am wondering why we need flags attribute ?
enum TestType { None = 0x0 , Type1 = 0x1 , Type2 = 0x2 }
Is flags attribute necessary ?
C#
I have a generic class A < T > , that implements IEnumerable < T [ ] > .I want to have a convenience wrapper B that inherits from A < char > and implements IEnumerable < string > .Now , this works perfectly fine , foreach variable type is inferred to be string : But this wo n't compile , saying `` The type arguments ca...
public class A < T > : IEnumerable < T [ ] > { public IEnumerator < T [ ] > GetEnumerator ( ) { return Enumerate ( ) .GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } protected IEnumerable < T [ ] > Enumerate ( ) { throw new System.NotImplementedException ( ) ; } } public c...
Multiple IEnumerable implementations paradox
C#
I just established a connection to SWI Prolog and want to manipulate facts . e.g . retract and assert them.I have some function like this : As you can see this function , it 's working for assertion as expected , but not for retract . The matter is that , I want to delete all tablets facts ( they are dynamic ) from fil...
String [ ] param = { `` -q '' } ; PlEngine.Initialize ( param ) ; PlQuery.PlCall ( `` consult ( 'tablets.pl ' ) . `` ) ; PlQuery.PlCall ( `` assert ( tablet ( 4 , newatomic ) ) . `` ) ; PlQuery.PlCall ( `` tell ( 'tablets.pl ' ) , listing ( tablet/2 ) , told . `` ) ; PlQuery.PlCall ( `` retractall ( tablet/2 ) . `` ) ;...
Prolog C # Interface retract from file
C#
I 'm trying to hold in memory a collection of references of type Action < T > where T is variable type I 've found a solution with dynamic but I would prefer not to use dynamic the solutionDoes anyone know a better approach to handling this ? Thanks in advance .
public class MessageSubscriptor : IMessageSubscriptorPool { Dictionary < Type , Action < dynamic > > Callbacks = new Dictionary < Type , Action < dynamic > > ( ) ; public void Subscribe < T > ( Action < T > callback ) where T : IMessage { Callbacks.Add ( typeof ( T ) , ( obj ) = > callback ( obj ) ) ; } }
Storing Action < T > in a single collection for later usage
C#
This is extremely slow : This is about 5x faster : Can anybody tell me why ?
try { x = k / y ; } catch ( DivideByZeroException ) { } if ( y > 0 ) x = k / y ;
DivideByZeroException too slow
C#
I have to query collection like this : s.CountryCode above is an example . I want to make it variable and call for different columns , like this : So I would like to define function where the column expression is a parameter . What is the signature of such function ? myList is an ObservableCollection , and myFilters is...
myList.Where ( s = > myFilters.Contains ( s.CountryCode ) ) myList.Where ( s = > myFilters.Contains ( s.City ) ) myList.Where ( s = > myFilters.Contains ( s.Region ) ) myList.Where ( s = > myFilters.Contains ( s.Zipcode ) ) public void MySelect ( ? ? ? ) { myList.Where ( s = > myFilters.Contains ( ? ? ? ) ; }
linq expression as parameter
C#
I have a marker interface something like this : And i want to apply it to methods on different classes in different assemblies ... Then I want to Get a MethodInfo for all methods that have this attribute applied . I need to search the whole AppDomain and get a reference to all these methods . I know we can get all type...
[ AttributeUsage ( AttributeTargets.Method , AllowMultiple=false , Inherited=true ) ] public class MyAttribute : Attribute { }
Is there a quicker/better way to get Methods that have attribute applied in C #
C#
Put default ( T ) in an interface . Explicitly implement the interface . The result does not compileI fully expect default ( ConcreteWhatever ) . What I get is default ( T ) which results in a compilation error . I just go in and replace default ( T ) with null and things are fine . But this is hideous . Why is this ha...
public interface IWhatever < T > { List < T > Foo ( T BarObject = default ( T ) ) ; } public class ConcreteWhatever : IWhatever < ConcreteWhatever > { List < ConcreteWhatever > Foo ( ConcreteWhatever BarObject = default ( T ) ) { } }
C # - How are we supposed to implement default ( T ) in Interfaces ?
C#
A bit of a conceptual question : I 'm creating my custom structure , in the vein of a Vector3 ( 3 int values ) and I was working through overloading the standard operators ( + , - , * , / , == etc ... ) As I 'm building a library for external use , I 'm attempting to conform to FxCop rules . As such , they recommend ha...
public static MyStruct operator + ( MyStruct struc1 , MyStruct struct2 ) { return struc1.Add ( struct2 ) ; } public MyStruct Add ( MyStruct other ) { return new MyStruct ( this.X + other.X , this.Y + other.Y , this.Z + other.Z ) ; } public static MyStruct operator + ( MyStruct struc1 , MyStruct struct2 ) { return new M...
Operator Overloading in C # - Where should the actual code code go ?
C#
Here is a simplified function that I want to create : In that code block , I get the compiler error : Error CS0029 Can not implicitly convert type 'System.Collections.Generic.List < > ' to 'System.Collections.Generic.List'In the documentation for Anonymous types , it says that anonymous types are treated as type object...
static List < object > GetAnonList ( IEnumerable < string > names ) { return names.Select ( name = > new { FirstName = name } ) .ToList ( ) ; } static IEnumerable < object > GetAnonList ( IEnumerable < string > names ) { return names.Select ( name = > new { FirstName = name } ) .ToList ( ) ; }
Why does n't IEnumerable of anonymous types return a List < object > on ToList ( ) ?
C#
I know I ca n't overload a return type ( I think I know this ) ... produces error already defines a member called ' F ' with the same parameter typesHowever , I 'm reading the documentation for ISet from MSDN , and I think I see the two Add methods that only vary by return type.What is going on here ?
void F ( ) { } bool F ( ) { return true ; }
How does ISet have two Add ( T item ) methods that vary only by return type ?
C#
I am trying to use the following custom task scheduler to limit concurrent web requests : I 'm using it like this : The problem is that the inner tasks are using my LimitedConcurrencyLevelTaskScheduler instead of the default TaskScheduler . This leads to self blocking and the output is like this : When I change the CON...
const int CONCURRENCY_LEVEL = 2 ; static void Main ( ) { TaskFactory factory = new TaskFactory ( new LimitedConcurrencyLevelTaskScheduler ( CONCURRENCY_LEVEL ) ) ; Task.WaitAll ( new [ ] { factory.StartNew ( ( ) = > SomeAction ( `` first '' ) ) , factory.StartNew ( ( ) = > SomeAction ( `` second '' ) ) } ) ; Console.Wr...
TaskScheduler with limited concurrency blocks itself
C#
I am trying to format some precise dates , converting them from a Unix timestamp to a DateTime object . I noticed that the AddSeconds method has an overload that accepts a floating point number.My expectation is that I may pass in a number such as 1413459415.93417 and it will give me a DateTime object with tick-level p...
public static DateTime CalendarDateFromUnix ( double unixTime ) { DateTime calendarTime = UnixEpoch.AddSeconds ( unixTime ) ; return calendarTime ; } dd MMM yyyy HH : mm : ss.fffff
Is .NET DateTime truncating my seconds ?
C#
I have two questions : 1 ) What is the fastest algorithm to put this list in a `` connecting '' order ? 2 ) Is this an existing problem/algorithm , and what name does it have ? The nodes are always connected in a circular fashion , so my starting ID does not matter . Given this list : node1 & node2 are not in a specifi...
id node1 node2A 4 9B 6 1C 1 3D 3 10E 7 2F 4 2G 9 8H 10 5I 7 5J 6 8 node ids : 4 - 9 - 8 - 6 - 1 - 3 - 10 - 5 - 7 - 2 - 4ids : A G J B C D H I E F
Fastest algorithm for a 'circular linked list builder '
C#
I want to upload a file ( VideoFile ) to server through BackgroundTransferService.My problem is , I also want to send 2 parameters along with File ( POST request ) .So , is it possible to send parameters along with File upload while using BackgroundTransferService API.. ? Code with BackgroundTransferService : Please as...
BackgroundTransferRequest req = new BackgroundTransferRequest ( new Uri ( `` ServerURL '' , UriKind.Absolute ) ) ; req.Method = `` POST '' ; req.TransferPreferences = TransferPreferences.AllowCellularAndBattery ; string uploadLocationPath = `` /Shared/Transfers/myVideoFile.mp4 '' ; string downloadLocationPath = `` /Sha...
BackgroundTransferService with POST method and Parameters
C#
So here 's what I 'm looking to achieve . I would like to give my users a single google-like textbox where they can type their queries . And I would like them to be able to express semi-natural language such asit 's ok if the syntax has to be fairly structured and limited to this specific domain ... these are expert us...
`` view all between 1/1/2008 and 1/2/2008 ''
Parsing a User 's Query
C#
I have a class library with numerous EF6 entities . I generated a NuGet from this library . Whenever I reference the library directly only the DLL is placed in the bin , however when I install the library via NuGet it copies over the entities *Content.tt and *.tt files into a folder in the project.I have a couple of qu...
< ? xml version= '' 1.0 '' ? > < package > < metadata > < id > MYID < /id > < version > 12.0.2 < /version > < title > MYTITLE < /title > < authors > MYNAME < /authors > < owners > < /owners > < requireLicenseAcceptance > false < /requireLicenseAcceptance > < description < /description > < releaseNotes > < /releaseNotes...
NuGet vs Direct Reference of Class w/ EF6 Entities
C#
I have a string like this : I want to do a replacement on this string such that each word ( case-insensitive ) will be matched , and replaced with a numbered index span tag like so : I tried doing it like this.The output is something like this : Where all the ids are the same ( m_1 ) because the regex does n't evaluate...
string s = `` < p > Hello world , hello world < /p > '' ; string [ ] terms = new string [ ] { `` hello '' , `` world '' } ; < p > < span id= '' m_1 '' > Hello < /span > < span id= '' m_2 '' > world < /span > , < span id= '' m_3 '' > hello < /span > < span id= '' m_4 '' > world < /span > ! < /p > int match = 1 ; Regex.R...
C # Regex change replacement string for each match
C#
I 'm toying around with the idea of using C # 's ability to compile code on-demand as the basis of a scripting language . I was wondering , how can I sandbox the scripts that I am executing so that they can not access the file system , network , etc . Basically , I want restricted permissions on the script being run.St...
CompilerResults r = CSharpCodeProvider.CompileAssemblyFromSource ( source ) ; Assembly a = r.CompiledAssembly ; IScript s = a.CreateInstance ( ... ) ; s.EntryPoint ( ... ) ;
Assembly.CreateInstance and security
C#
I was trying to create my own factorial function when I found that the that the calculation is twice as fast if it is calculated in pairs . Like this : Groups of 1 : 2*3*4 ... 50000*50001 = 4.1 secondsGroups of 2 : ( 2*3 ) * ( 4*5 ) * ( 6*7 ) ... ( 50000*50001 ) = 2.0 secondsGroups of 3 : ( 2*3*4 ) * ( 5*6*7 ) ... ( 49...
Stopwatch timer = new Stopwatch ( ) ; timer.Start ( ) ; // Seperate the calculation into groups of this size.int k = 2 ; BigInteger total = 1 ; // Iterates from 2 to 50002 , but instead of incrementing ' i ' by one , it increments it ' k ' times , // and the inner loop calculates the product of ' i ' to ' i+k ' , and m...
Why is it faster to calculate the product of a consecutive array of integers by performing the calculation in pairs ?
C#
I have a Main method like this : Since I am accessing a local variable b here the compiler creates a class to capture that variable and b becomes the field of that class . Then the b lives as long as the life time of the compiler generated class and it causes a memory leak . Even if b goes out of scope ( maybe not in t...
static void Main ( string [ ] args ) { var b = new byte [ 1024 * 1024 ] ; Func < double > f = ( ) = > { new Random ( ) .NextBytes ( b ) ; return b.Cast < int > ( ) .Average ( ) ; } ; var avg = f ( ) ; Console.WriteLine ( avg ) ; } Func < double > f = ( ) = > { var b = new byte [ 1024 * 1024 ] ; new Random ( ) .NextByte...
Why ca n't the compiler optimize closure variable by inlining ?
C#
I have the following entities : An account class with a list of subscriptions : the subscription class with a list of variations and add ons : the add on class with a list of variations : And the variation class : What I 'm trying to do is to group all add ons with specific Code and sum the quantity . For example I tri...
public class Account { /// < summary > /// Account ID /// < /summary > public string ID { get ; set ; } /// < summary > /// A List with all subscriptions /// < /summary > public IEnumerable < Subscription > Subscriptions { get ; set ; } } public class Subscription { /// < summary > /// Subscription ID /// < /summary > ...
Linq Group by and sum problems
C#
I want to create a new group when the difference between the values in rows are greater then five.Example : should give me 3 groups : Is it possible to use Linq here ? Thx !
int [ ] list = { 5,10,15,40,45,50,70,75 } ; 1 , [ 5,10,15 ] 2 , [ 40,45,50 ] 3 , [ 70,75 ]
How can I group by the difference between rows in a column with linq and c # ?
C#
Databound to an ObservableCollection , I am filling an ItemsControl with Buttons . I am using UniformGrid to help evenly spread things out whether there are 5 or 5000 objects in the ObservableCollection . Desire : After the user searches/filters the ObservableCollection , I would like to update an IsVisible property on...
< ItemsControl Name= '' ItemsList '' Width= '' Auto '' HorizontalContentAlignment= '' Left '' ItemsSource= '' { Binding ItemsVM.WorkList } '' ScrollViewer.CanContentScroll= '' True '' VirtualizingStackPanel.IsVirtualizing= '' true '' VirtualizingStackPanel.VirtualizationMode= '' Standard '' > < ItemsControl.ItemsPanel ...
WPF - Hide items in ItemControl - > UniformGrid from taking up UI space based on databinding
C#
In my current application , I have the following MongoDB FindAndModify call to the MongoDB server Am I reinventing yet another queue system with MongoDB ? That 's not my intention here but it 's what it 's . Just ignore the business logic there.In CQRS , Query and Command mean the following ( I believe ) : Command : Ch...
public static TEntity PeekForRemoveSync < TEntity > ( this MongoCollection < TEntity > collection , string reason ) where TEntity : class , IEntity , IUpdatesTrackable , ISyncable , IDeletable , IApprovable { if ( reason == null ) { throw new ArgumentNullException ( nameof ( reason ) ) ; } IMongoQuery query = Query.And...
Where does FindAndModify fit into CQRS ?
C#
I declare a Byte-Array like this : and assign some values : Now I want to zero the array again and call : which does n't work . The array remains unchanged . Is n't b a value-type array ?
Byte [ ] b = new Byte [ 10 ] ; for ( int i=0 ; i < b.Length ; i++ ) { b [ i ] = 1 ; } b.Initialize ( ) ;
C # : Why does n't Initialize work with a Byte-Array ?
C#
Assume we have this model : I created a extension method for all classes that inherit from AbstractTableReferentielEntity.But for one specific type of AbstractTableReferentielEntity ( like EstimationTauxReussite ) , I would like to perform a specific action , so I created a second extension method.All extensions method...
public abstract class AbstractTableReferentielEntity { } public class EstimationTauxReussite : AbstractTableReferentielEntity { } public static EntityItemViewModel ToEntityItem < T > ( this T entity ) where T : AbstractTableReferentielEntity { } public static EntityItemViewModel ToEntityItem ( this EstimationTauxReussi...
Extension methods with interface
C#
I 'm currently working on a desktop tool in .NET Framework 4.8 that takes in a list of images with potential cracks and uses a model trained with ML.Net ( C # ) to perform crack detection . Ideally , I 'd like the prediction to take less than 100ms on 10 images ( Note : a single image prediction takes between 36-41ms )...
MLContext mlContext = new MLContext ( ) ; IDataView inputData = mlContext.Data.LoadFromEnumerable ( inputDataEnumerable ) ; IDataView results = _LoadedModel.Transform ( inputData ) ; var imageClassificationPredictions = mlContext.Data.CreateEnumerable < ImageClassificationPrediction > ( results , false ) .ToList ( ) ;
C # ML.Net Image classification : Does GPU acceleration help improve the performance of predictions and how can I tell if it is ?
C#
Causes : Struct member 'Unit.u ' of type 'Unit ' causes a cycle in the struct layout.Butcompiles . I understand the problem I suppose . An endless cycle will be formed when referencing a Unit object since it will have to initialize another member Unit and so on . But why does the compiler restrict the problem just for ...
public struct Unit { Unit u ; } public class Unit { Unit u ; }
Why is there no cyclic layout issue for classes in C # ?
C#
I created a simple UWP application with no code , just XAML.If I zoom in to about US state level , the application will crash with an unhandled exception.The event viewer Application Log shows : I 'm running on Windows 10 Version 20H2 ( OS Build 19042.630 ) .How can I fix or diagnose this crash further ? Update 1I was ...
< Grid > < maps : MapControl/ > < /Grid > Faulting module name : ucrtbase.dll , version : 10.0.19041.546 , time stamp : 0x43cbc11dException code : 0xc0000409 ucrtbase.dll ! abort ( ) Unknown ucrtbase.dll ! terminate ( ) Unknown ucrtbase.dll ! __crt_state_management : :wrapped_invoke < void ( * ) ( void ) , void > ( voi...
UWP MapControl crashes after zooming in
C#
I am writing a method that will take a screenshot of a passed form element , and print it out . There are a few challenges I am facing . I want to be able to make this method generic enough to accept just about any type of form element . I set the `` element '' argument to type `` object '' . I think I will also need t...
static public void PrintFormElement ( object element , ? type ? ) { }
Accepting Form Elements As Method Arguments ?
C#
How do I convert this date to `` 20110504 14:33:41 '' ?
DateTime date = DateTime.Parse ( `` 2011-05-04 14:33:41 '' ) ; //4 may 2011
DateTime format string
C#
I 'm having a hard time understanding why it would be beneficial to do something like this : ( Sample is a class ) Would n't it be better to to just pass Sample into the method ?
static void PrintResults < T > ( T result ) where T : Sample static void PrintResults ( Sample result )
What is the purpose of a restricting the type of generic in a method ?
C#
The following pair of functions attempt to replicate the null conditional operator available in C # 6.0 : The first function is constrained to classes and for a String s allows me to write something like : The second function is where I am running into trouble . For example , given a int ? number I would like to write ...
public static TResult Bind < T , TResult > ( this T obj , Func < T , TResult > func ) where T : class { return obj == null ? default ( TResult ) : func ( obj ) ; } public static TResult Bind < T , TResult > ( this Nullable < T > obj , Func < T , TResult > func ) where T : struct { return obj.HasValue ? func ( obj.Value...
C # why is this type inferred method call ambiguous ?
C#
If there are n properties , then is the Big-O of .GetProperties O ( n ) or are there are processes involved in the reflection that add complexity ? Say there is this defined class : And then this call is made : What is the time complexity , i.e . Big-O , of .GetProperties ( ) ? Considering that there are 4 properties ,...
public class Reflector { public string name { get ; set ; } public int number { get ; set ; } public bool flag { get ; set ; } public List < string > etc { get ; set ; } } var reflect = new Reflector ( ) ; PropertyInfo [ ] properties = reflect.GetType ( ) .GetProperties ( ) ;
Big-O of .GetProperties ( )
C#
I am trying to understand how events can cause a memory leak . I found a good explaination at this stackoverflow question but when looking at objects in Windg , I am getting confused with the result . To start with , I have a simple class as follows.Now I am using this class in a windows form application as follows.As ...
class Person { public string LastName { get ; set ; } public string FirstName { get ; set ; } public event EventHandler UponWakingUp ; public Person ( ) { } public void Wakeup ( ) { Console.WriteLine ( `` Waking up '' ) ; if ( UponWakingUp ! = null ) UponWakingUp ( null , EventArgs.Empty ) ; } } public partial class Fo...
Why this does not cause a memory leak when event is not unsubscribed
C#
I want to iterate through an enum so I can call a method with each value of that enum . How can I do that ? I want it instead to be something likeIs there a way to do this ?
enum Base { ANC , BTC , DGC } ; XmlDocument doc ; doc = vircurex.get_lowest_ask ( Base.ANC ) doc = vircurex.get_lowest_ask ( Base.BTC ) doc = vircurex.get_lowest_ask ( Base.DGC ) foreach ( var val in values ) doc = vircurex.get_lowest_ask ( ... . )
How to iterate through an enum in C # ?
C#
The example php regex ( below ) uses subroutine calls to work.If I try use it with the C # Regex class I get an error : Unrecognized grouping constructIs it possible to rewrite this in to C # regex syntax ? Would it be a simple translation , or does another ( regex ) approach need to be used ? If it is not possible wha...
$ pcre_regex = ' / ( ? ( DEFINE ) ( ? < number > - ? ( ? : [ 1-9 ] \d*| 0 ) ( \.\d+ ) ? ( e [ +- ] ? \d+ ) ? ) ( ? < boolean > true | false | null ) ( ? < string > `` ( ? > [ ^ '' \\\\ ] + | \\\\ [ `` \\\\bfnrt\/ ] | \\\\ u [ 0-9a-f ] { 4 } ) * `` ) ( ? < array > \ [ ( ? : ( ? & json ) ( ? : , ( ? & json ) ) * ) ? \s* ...
Is it possible to convert PHP Regex ( using subroutine calls ) to C # regex ?
C#
I noticed something in C # when dealing with custom objects that I found to be a little odd . I am certain it is just a lack of understanding on my part so maybe someone can enlighten me.If I create a custom object and then I assign that object to the property of another object and the second object modifies the object...
class MyProgram { static void Main ( ) { var myList = new List < string > ( ) ; myList.Add ( `` I was added from MyProgram.Main ( ) . `` ) ; var myObject = new SomeObject ( ) ; myObject.MyList = myList ; myObject.DoSomething ( ) ; foreach ( string s in myList ) Console.WriteLine ( s ) ; // This displays both strings . ...
C # odd object behavior
C#
All these string prefixes are legal to use in C # : Why is n't this ? One would have thought that the order of these operators does n't matter , because they have no other meaning in C # but to prefix strings . I can not think of a situation when this inverted double prefix would not compile . Is the order enforced onl...
`` text '' @ '' text '' $ '' text '' $ @ '' text '' @ $ '' text ''
Why ca n't I use @ $ prefix before strings ?
C#
Guys I have a `` best practice question '' For example I have this classes : What is recommended to pass ? Just what I need ( int-value type ) or the whole object ( reference type ) Im asking this because Im using LINQ on an app that I am making and I have created many entities where I should pass the IDs ( foreing key...
class Person { public int age { get ; set ; } } class Computer { public void checkAge ( Person p ) // Which one is recommended THIS { // Do smthg with the AGE } public void checkAge ( int p ) // OR THIS { //Do smthg with the age . } }
What to pass ? Reference Object or Value Type ?