lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
When I remove Ldstr `` a '' and Call Console.WriteLine ( before Ret ) , the code runs fine , otherwise an InvalidProgramException is thrown upon invocation . Does this mean that an empty evaluation stack is required ?
class Program { delegate void Del ( ) ; static void Main ( string [ ] args ) { DynamicMethod dynamicMethod = new DynamicMethod ( `` '' , null , Type.EmptyTypes ) ; ILGenerator ilGen = dynamicMethod.GetILGenerator ( ) ; ilGen.Emit ( OpCodes.Ldstr , `` a '' ) ; ilGen.BeginExceptionBlock ( ) ; ilGen.Emit ( OpCodes.Ldstr ,...
Is an empty evaluation stack required before an exception block ?
C#
or
db.Albums.FirstOrDefault ( x = > x.OrderId == orderId ) db.Albums.FirstOrDefault ( x = > x.OrderId.Equals ( orderId ) )
Linq to SQL - what 's better ?
C#
I have the next function : I inserted the print function for analysis.If I call the function : It return true since 5^2 equals 25.But , if I call 16807 , which is 7^5 , the next way : In this case , it prints ' 7 ' but a == ( int ) a return false.Can you help ? Thanks !
static bool isPowerOf ( int num , int power ) { double b = 1.0 / power ; double a = Math.Pow ( num , b ) ; Console.WriteLine ( a ) ; return a == ( int ) a ; } isPowerOf ( 25 , 2 ) isPowerOf ( 16807 , 5 )
C # isPowerOf function
C#
Can someone explain the following piece of codeIt assigns 32 to y
int x = 45 ; int y = x & = 34 ;
How does this C # code snippet work ?
C#
While testing an application , I ran a into strange behaviour . Some of the tests use impersonation to run code as a different user , but they would always hang , never complete.After some investigation , the problem was narrowed down to the use of mutexes . Originally , we used our own impersonation code based on the ...
using ( Impersonation.LogonUser ( DOMAIN , USER , PASSWORD , LogonType.Interactive ) ) { Console.WriteLine ( `` Impersonated '' ) ; bool mine ; using ( new Mutex ( true , `` Mutex '' , out mine ) ) { if ( ! mine ) throw new Exception ( `` Could n't get mutex '' ) ; Console.WriteLine ( `` Got mutex '' ) ; } } Console.Wr...
Mutex creation hangs while using impersonation
C#
I have a LINQ statement which is adding up the values of multiple columns , each beginning with 'HH ' although there are other columns available : Is there any way to tidy this up ? I have to do lots of variations of this ( in different methods ) so it would clear out a lot of 'fluff ' if it could be.Also I 'd like to ...
//TODO Clean up this messvar query1 = ( from e in Data where e.SD == date select e ) .Select ( x = > x.HH01 + x.HH16 + x.HH17 + x.HH18 + x.HH19 + x.HH20 + x.HH21 + x.HH22 + x.HH23 + x.HH24 + x.HH25 + x.HH26 + x.HH27 + x.HH28 + x.HH29 + x.HH30 + x.HH31 + x.HH32 + x.HH33 + x.HH34 + x.HH35 + x.HH36 + x.HH37 + x.HH38 + x.H...
Ugly LINQ statement , a better way ?
C#
While looking at the Implementation of List.AddRange i found something odd i do not understand.Sourcecode , see line 727 ( AddRange calls InsertRange ) Why doest it Copy the collection into a `` temp-array '' ( itemsToInsert ) first and then copies the temp array into the actual _items-array ? Is there any reason behin...
T [ ] itemsToInsert = new T [ count ] ; c.CopyTo ( itemsToInsert , 0 ) ; itemsToInsert.CopyTo ( _items , index ) ;
List < T > .AddRange / InsertRange creating temporary array
C#
I have an overload method - the first implementation always returns a single object , the second implementation always returns an enumeration.I 'd like to make the methods generic and overloaded , and restrict the compiler from attempting to bind to the non-enumeration method when the generic type is enumerable ... To ...
class Cache { T GetOrAdd < T > ( string cachekey , Func < T > fnGetItem ) where T : { is not IEnumerable } { } T [ ] GetOrAdd < T > ( string cachekey , Func < IEnumerable < T > > fnGetItem ) { } } { // The compile should choose the 1st overload var customer = Cache.GetOrAdd ( `` FirstCustomer '' , ( ) = > context.Custo...
an I prevent a specific type using generic restrictions
C#
I always thought it worked fine both ways . Then did this test and realized it 's not allowed on re-assignments : works fine but not : Any technical reason for this ? I thought I would ask about it here , because this behavior was what I expected intuitively .
int [ ] a = { 0 , 2 , 4 , 6 , 8 } ; int [ ] a ; a = { 0 , 2 , 4 , 6 , 8 } ;
Why are collection initializers on re-assignments not allowed ?
C#
I am wondering if there is some way to optimize the using statement to declare and assign its output together ( when it is a single value ) .For instance , something similar to the new way to inline declare the result variable of an out parameter.Thanks for your input .
//What I am currently doing : string myResult ; using ( var disposableInstance = new myDisposableType ( ) ) { myResult = disposableInstance.GetResult ( ) ; } //That would be idealvar myResult = using ( var disposableInstance = new myDisposableType ( ) ) { return disposableInstance.GetResult ( ) ; } //That would be grea...
C # using statement with return value or inline declared out result variable
C#
The following VB.NET code works : The following C # code fails to compile : The LearnerLogbookReportRequest is declared as : Error : Why is the C # version failing to compile ?
Dim request As Model.LearnerLogbookReportRequest = New Model.LearnerLogbookReportRequestrequest.LearnerIdentityID = Convert.ToInt32 ( Session ( `` identityID '' ) ) request.EntryVersion = LearnerLogbookEntryVersion.FullDim reportRequestService As IReportRequestService = ServiceFactory.GetReportRequestService ( ServiceI...
Why does my code compile in VB.NET but the equivalent in C # fails
C#
Hi my head is boiling now for 3 days ! I want to get all DNA encodings for a peptide : a peptide is a sequence of amino acids i.e . amino acid M and amino acid Q can form peptide MQ or QMDNA encoding means there is a DNA code ( called codon ) for each amino acid ( for some there are more than one code i.e . amino acid ...
private string [ ] CODONS = { `` TTT '' , `` TTC '' , `` TTA '' , `` TTG '' , `` TCT '' , `` TCC '' , `` TCA '' , `` TCG '' , `` TAT '' , `` TAC '' , `` TGT '' , `` TGC '' , `` TGG '' , `` CTT '' , `` CTC '' , `` CTA '' , `` CTG '' , `` CCT '' , `` CCC '' , `` CCA '' , `` CCG '' , `` CAT '' , `` CAC '' , `` CAA '' , ``...
how to get all dna encoding for peptide in c #
C#
I want to prohibit reentrancy for large set of methods.for the single method works this code : This is tedious to do it for every method.So I 've used StackTrace class : It works fine but looks more like a hack.Does .NET Framework have special API to detect reentrancy ?
bool _isInMyMethod ; void MyMethod ( ) { if ( _isInMethod ) throw new ReentrancyException ( ) ; _isInMethod = true ; try { ... do something ... } finally { _isInMethod = false ; } } public static void ThrowIfReentrant ( ) { var stackTrace = new StackTrace ( false ) ; var frames = stackTrace.GetFrames ( ) ; var callingM...
Does framework have dedicated api to detect reentrancy ?
C#
I 'm newer to C # and have just discovered how to use yield return to create a custom IEnumerable enumeration . I 'm trying to use MVVM to create a wizard , but I was having trouble figuring out how to control the flow from one page to the next . In some cases I might want a certain step to appear , in others , it does...
public class HPLDTWizardViewModel : WizardBase { protected override IEnumerable < WizardStep > Steps { get { WizardStep currentStep ; // 1.a start with assay selection currentStep = new AssaySelectionViewModel ( ) ; yield return currentStep ; // 1.b return the selected assay . SigaDataSet.Assay assay = ( ( AssaySelecti...
Wizard navigation with IEnumerable / yield return
C#
Ok , this is a little weird . Ignore what I am trying to do , and look at the result of what happens in this situation.The Code : The Situation : The line numbers = rawNumbers.Split ( ' , ' ) .Cast < int > ( ) ; appears to work , and no exception is thrown . However , when I iterate over the collection , and InvalidCas...
static string rawNumbers= '' 1,4,6,20,21,22,30,34 '' ; static IEnumerable < int > numbers = null ; static void Main ( string [ ] args ) { numbers = rawNumbers.Split ( ' , ' ) .Cast < int > ( ) ; for ( int i = 0 ; i < numbers.Count ( ) ; i++ ) { //do something } } static IEnumerable < TResult > CastIterator < TResult > ...
Did I really just put a string data type into an IEnumerable < int >
C#
I migrated an WebAPI from FullDotnet ( 4.6 ) to .Net Core 2.0 and I 'm having this issue in my Data Layer using Dapper.My code : Strange Behavior : The solution Builds and WORKThe `` error '' who VisualStudio highlight is : Argument type 'lambda expression ' is not assignable to parameter type 'System.Func ` 5 ' I have...
public List < Doctor > GetList ( ) { List < Doctor > ret ; using ( var db = GetMySqlConnection ( ) ) { const string sql = @ '' SELECT D.Id , D.Bio , D.CRMState , D.CRMNumber , U.Id , U.Email , U.CreatedOn , U.LastLogon , U.Login , U.Name , U.Phone , U.Surname , U.Id , U.Birth , U.CPF , S.Id , S.Name from Doctor D inner...
Why does Visual Studio report a lambda error in a working WebAPI code on .Net Core ?
C#
I 've read this answer and understood from it the specific case it highlights , which is when you have a lambda inside another lambda and you do n't want to accidentally have the inner lambda also compile with the outer one . When the outer one is compiled , you want the inner lambda expression to remain an expression ...
private static void TestMethodCallCompilation ( ) { var methodInfo = typeof ( Program ) .GetMethod ( `` GimmeExpression '' , BindingFlags.NonPublic | BindingFlags.Static ) ; var lambdaExpression = Expression.Lambda < Func < bool > > ( Expression.Constant ( true ) ) ; var methodCallExpression = Expression.Call ( null , ...
Why would you quote a LambdaExpression ?
C#
We have a web api with the following resource url.now there are some books which contains names with ampersand ' & ' and when a request is made for such names , we are receiving below errorURL used : Error : A potentially dangerous Request.Path value was detected from the client ( & ) We tried passing or using encoded ...
http : //www.example.com/book/bookid/name/bookname http : //www.example.com/book/123/name/ban & ban http : //www.example.com/book/123/name/ban % 26ban
error when url resource contains ampersand
C#
I have a RGB image ( RGB 4:4:4 colorspace , 24-bit per pixel ) , captured from camera . I use Gorgon 2D library ( build base on SharpDX ) to display this image as a texture so i have to convert it to ARGB . I use this code ( not my code ) to convert from RGB camera image to RGBA.Then convert RGB to RGBA like this : And...
[ StructLayout ( LayoutKind.Sequential ) ] public struct RGBA { public byte r ; public byte g ; public byte b ; public byte a ; } [ StructLayout ( LayoutKind.Sequential ) ] public struct RGB { public byte r ; public byte g ; public byte b ; } unsafe void internalCvt ( long pixelCount , byte* rgbP , byte* rgbaP ) { for ...
How to convert RGB camera image to ARGB format of SharpDX ?
C#
Anyone can elaborate some details on this code or even give a non-Linq version of this algorithm :
public static IEnumerable < IEnumerable < T > > Combinations < T > ( this IEnumerable < T > elements , int k ) { return k == 0 ? new [ ] { new T [ 0 ] } : elements.SelectMany ( ( e , i ) = > elements .Skip ( i + 1 ) .Combinations ( k - 1 ) .Select ( c = > ( new [ ] { e } ) .Concat ( c ) ) ) ; }
How to understand the following C # linq code of implementing the algorithm to return all combinations of k elements from n
C#
I have seen people use a couple of different way of initializing arrays : or another way , also called initializing is : What is the best way , and what is the major difference between both ways ( including memory allocation ) ?
string [ ] Meal = new string [ ] { `` Roast beef '' , `` Salami '' , `` Turkey '' , `` Ham '' , `` Pastrami '' } ; string [ ] Meats = { `` Roast beef '' , `` Salami '' , `` Turkey '' , `` Ham '' , `` Pastrami '' } ;
Whats the difference between Declaring a variable ( as new ) and then initializing it and direct initializing it ?
C#
I 'm looking to implement some algorithm to help me match imperfect sequences.Say I have a stored sequence of ABBABABBA and I want to find something that 'looks like ' that in a large stream of characters.If I give my algorithm the allowance to have 2 wildcards ( differences ) , how can I use Regex to match something l...
A ( A ) BABAB ( A ) A or ( B ) BBA ( A ) ABBA ABBDBABDBCBDBABDB ( A ( A ) BABAB ( A ) A ) DBDBABDBCBDBABADBDBABDBDBDBCBDBABCBDBABCBDBABCBDBABABBBDBABABBCDDBABCBDABDBABCBCBDBABABDABDBABCBDBABABDDABCBDBABAB
Regex to find 'good enough ' sequences
C#
I 'm working on my final year project . In which : I have Login and Signup forms on one page ( WebForm ) : When user click on anchor Sign Up the DropDown ddlType ( hides ) and TextBoxes - txtCustName , txtEmail and txtConfirmPassword ( Displays ) in Javascript client side : Login Form : -And when user click on anchor L...
function signupClick ( ) { document.getElementById ( 'divType ' ) .style.display = 'block ' ? 'none ' : 'block ' ; document.getElementById ( ' < % =txtCustName.ClientID % > ' ) .style.display = 'inherit ' ; document.getElementById ( ' < % =txtConfirmPassword.ClientID % > ' ) .style.display = 'inherit ' ; document.getEl...
How to stop on the Sign Up Form when web page performs Postback ?
C#
I 'm having problem with finding most common group of integers among int [ x,6 ] array , where x < = 100000 . Numbers are between 0 and 50.eg input . ( N = 2 ) output : Attached code I tried . Now I understand it does n't work , but I was asked me to post it . I 'm not just asking help without even trying .
14 24 44 36 37 45 - here01 02 06 24 33 4410 17 34 40 44 45 - here12 13 28 31 37 4701 06 07 09 40 4501 05 06 19 35 4413 19 20 26 31 4744 20 30 31 45 46 - here02 04 14 23 30 3427 30 41 42 44 4903 06 15 27 37 48 44 , 45 ( 3 ) // appeared 3 times using System ; using System.Collections.Generic ; using System.Linq ; using S...
How to find a group of integers ( N ) amongst records , that contains 6 integers
C#
I found this code snippet on SO ( sorry I do n't have the link to the question/answer combo ) This confuses me because FileAttributes.Directory is on both sides of the ==.What does the & do in this case ? I 'm not sure how to read this line of code . I 'm trying to evaluate whether a path string is a file or a director...
bool isDir = ( File.GetAttributes ( source ) & FileAttributes.Directory ) == FileAttributes.Directory ;
How does this C # operator work in this code snippet ?
C#
I 've got a controller method : Now , I 'd like to test this.This throws a RuntimeBinderException saying that Calculated is not defined . Is there any way to achieve this ? UPDATEFollowing Jons ' advice , I used InternalsVisibleTo to befriend my test assembly . Everything works fine . Thank you Jon .
public JsonResult CalculateStuff ( int coolArg ) { if ( calculatePossible ) return Json ( CoolMethod ( coolArg ) ) ; else return Json ( new { Calculated = false } ) ; } public void MyTest { var controller = GetControllerInstance ( ) ; var result = controller.CalculateStuff ( ) .Data as dynamic ; Assert.IsTrue ( result....
Using dynamic in C # to access field of anonymous type - possible ?
C#
Is there a more efficient way of doing the following , something just feels wrong about it ? I 'm looking for the most time efficient way of logging logarithmically.Update : Here are my micro benchmark tests.Method1 : Übercoder 's way with keep up with stateMethod2 : My way with the big switch statementMethod3 : Markus...
public bool Read ( ) { long count = Interlocked.Increment ( ref _count ) ; switch ( count ) { case 1L : case 10L : case 100L : case 1000L : case 10000L : case 100000L : case 1000000L : case 10000000L : case 100000000L : case 1000000000L : case 10000000000L : case 100000000000L : case 1000000000000L : case 1000000000000...
Logging logarithmically 1 , 10 , 100 , 1000 , etc
C#
I want to find the closest transaction amount which is closest ( which should be > = transaction amount ) or equal to single transaction amount of the given number , but it should be minimum amount . there will be many combination of data which is > = given number but out of those combination I want minimum transaction...
class Program { static void Main ( string [ ] args ) { string input ; decimal transactionAmount ; decimal element ; do { Console.WriteLine ( `` Please enter the transaction amount : '' ) ; input = Console.ReadLine ( ) ; } while ( ! decimal.TryParse ( input , out transactionAmount ) ) ; Console.WriteLine ( `` Please ent...
Get closest value from list by summation or exact single value using C #
C#
I have a method that is defined like such : I would like to do something like : My challenge is , I 'm not sure how to detect whether my propertyValue is a nullable bool or not . Can someone tell me how to do this ? Thank you !
public bool IsValid ( string propertyName , object propertyValue ) { bool isValid = true ; // Validate property based on type here return isValid ; } if ( propertyValue is bool ? ) { // Ensure that the property is true }
Detecting nullable types in C #
C#
I have started to understand that I do not understand what is going on . There is the following behavior in C # : It will print public void Method ( B a ) instead of public void Method ( D a ) It 's surprising . I suppose that the reason of this behavior is implementation of methods table . CLR does not search methods ...
public class Base { public void Method ( D a ) { Console.WriteLine ( `` public void Method ( D a ) '' ) ; } } public class Derived : Base { public void Method ( B a ) { Console.WriteLine ( `` public void Method ( B a ) '' ) ; } } public class B { } public class D : B { } class Program { static void Main ( string [ ] ar...
Overloading methods in inherited classes
C#
My code below finds all prime numbers below number by creating a list of primes and checking to see if the next potential prime is evenly divisible by any primes in the list.I 'm trying to learn the ins and outs of yield return . Right now I have a List < int > primes that I use inside the function . But I 'm returning...
/// < summary > /// Finds all primes below < paramref name= '' number '' / > /// < /summary > /// < param name= '' number '' > The number to stop at < /param > /// < returns > All primes below < paramref name= '' number '' / > < /returns > private static IEnumerable < long > PrimeNumbers ( long number ) { yield return ...
Can you access the IEnumerable as you are yield returning it ?
C#
I am trying to understand how async/await keywords works . I have a textblock on a WPF window bind to a TextBlockContent string property and a button which trigger on click ChangeText ( ) .Here is my code : From my readings , I understood that ConfigureAwait set to false would allow me to specify that I do not want to ...
public async void ChangeText ( ) { string mystring = await TestAsync ( ) ; this.TextBlockContent= mystring ; } private async Task < string > TestAsync ( ) { var mystring = await GetSomeString ( ) .ConfigureAwait ( false ) ; mystring = mystring + `` defg '' ; return mystring ; } private Task < string > GetSomeString ( )...
Why am I still on the Main Thread when I specified ConfigureAwait ( false ) ?
C#
I 'm attempting to grab a device handle on the Synaptics Touchpad using the Synaptics SDK , specifically using methods in the SYNCTRLLib . However , the SYNCTRL method failed to find it , returning -1.Syn.cs : Program.cs
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using SYNCOMLib ; using SYNCTRLLib ; namespace TP_Test1 { class Syn { SynAPICtrl SynTP_API = new SynAPICtrl ( ) ; SynDeviceCtrl SynTP_Dev = new SynDeviceCtrl ( ) ; SynPacketCtrl SynTP_Pack = new SynP...
Synaptics SDK ca n't find device
C#
I 'm in a little bit of a bind . I 'm working with a legacy system that contains a bunch of delimited strings which I need to parse . Unfortunately , the strings need to be ordered based on the first part of the string . The array looks something likeSo I 'd like the array to order to look likeI thought about doing a 2...
array [ 0 ] = `` 10|JohnSmith|82 '' ; array [ 1 ] = `` 1|MaryJane|62 '' ; array [ 2 ] = `` 3|TomJones|77 '' ; array [ 0 ] = `` 1|MaryJane|62 '' ; array [ 1 ] = `` 3|TomJones|77 '' ; array [ 2 ] = `` 10|JohnSmith|82 '' ;
How to numerically order array of delimited strings in C #
C#
I 'm facing a deadlock-issue in a piece of code of mine . Thankfully , I 've been able to reproduce the problem in the below example . Run as a normal .Net Core 2.0 Console application.What I 'd expect is the complete sequence as follows : However , the actual sequence stalls on the Thread.Join call : Finally , if I in...
class Class2 { static void Main ( string [ ] args ) { Task.Run ( MainAsync ) ; Console.WriteLine ( `` Press any key ... '' ) ; Console.ReadKey ( ) ; } static async Task MainAsync ( ) { await StartAsync ( ) ; //await Task.Delay ( 1 ) ; //a little delay makes it working Stop ( ) ; } static async Task StartAsync ( ) { var...
What 's causing a deadlock ?
C#
I have a class Player that implements ICollidable . For debugging purposes I 'm just trying to pass a bunch of ICollidables to this method and do some special stuff when it 's the player . However when I try to do the cast to Player of the ICollidable I get an error telling me that ICollidable does n't have a Color pro...
private Vector2 ResolveCollision ( ICollidable moving , ICollidable stationary ) { if ( moving.Bounds.Intersects ( stationary.Bounds ) ) { if ( moving is Player ) { ( Player ) moving.Color = Color.Red ; } } // ... }
Why is this cast from interface to class failing ?
C#
I have simple ASP.NET Core WebApi with modeland endpointWhen I make a POST request with bodyorthen model.Value == trueHow to avoid this ? I need some error in this case , because 7676 is not the Boolean value.I found this question and this , but solution is not fit for me , because I have a many models in different pro...
public class Model { public bool ? Value { get ; set ; } } [ HttpPost ] public async Task < IActionResult > Create ( [ FromBody ] Model model ) { `` Value '' : 7676 } { `` Value '' : 2955454545645645645645645645654534534540 }
Avoid bind any number to bool property
C#
I recently ran into an interesting issue with changing CASE statements to ISNULL functions in TSQL . The query I was working with is used to get some user attributes and permissions for a website I work on . Previously the query had a number of CASE statements similar to the following : NOTE : a.column1 in the example ...
SELECT ... CASE WHEN a.column1 IS NULL THEN 0 ELSE a.column1 END [ CanDoSomething ] ... FROM a SELECT ... ISNULL ( a.column1 , 0 ) [ CanDoSomething ] ... FROM a
ISNULL vs CASE Return Type
C#
All C # beginners know that class is a reference type and struct is a value one.Structures are recommended for using as simple storage.They also can implement interfaces , but can not derive from classes and can not play a role of base classes because of rather `` value '' nature.Assume we shed some light on main diffe...
public class SampleClass { public void AssignThis ( SampleClass data ) { this = data ; //Will not work as `` this '' is read-only } } public struct SampleStruct { public void AssignThis ( SampleStruct data ) { this = data ; //Works fine } }
C # hack : assignment to `` this ''
C#
I have a condition with two value . if the condition equal to 0 it return Absent and if equal to 1 it returns present.now I want to add the third value into my condition . if the condition equal to 3 it returns Unacceptable absent.this is my conditions with two value : how can I change the condition ?
( status > = 1 ? `` Present '' : `` Absent '' )
how can I change this condition to that I want
C#
Description : I am modifying the ASP.NET Core Web API service ( hosted in Windows Service ) that supports resumable file uploads . This works fine and resumes file uploads in many failure conditions except one described below.Problem : When the service is on ther other computer and the client is on mine and I unplug th...
public static async Task < List < ( Guid , string ) > > StreamFileAsync ( this HttpRequest request , DeviceId deviceId , FileTransferInfo transferInfo ) { var boundary = GetBoundary ( MediaTypeHeaderValue.Parse ( request.ContentType ) , DefaultFormOptions.MultipartBoundaryLengthLimit ) ; var reader = new MultipartReade...
Web API service hangs on reading the stream
C#
I have the following code : Why does n't the marked line compile ? Does it have something to do with return type not being part of the signature ? But the third line does compile , which makes me guess the compiler turns it into something similiar to the second line ...
public static class X { public static C Test < A , B , C > ( this A a , Func < B , C > f ) where C : class { return null ; } } public class Bar { public Bar ( ) { this.Test ( foo ) ; //this does n't compile this.Test ( ( Func < int , string > ) foo ) ; this.Test ( ( int q ) = > `` xxx '' ) ; } string foo ( int a ) { re...
C # Infer generic type based on passing a delegate
C#
In my templates I 've got these repeating blocks of content which I want to abstract to a single component : Normally I would use a razor partial view for this , and pass it some variables . However in this case that would mean passing big chunks of html as variables , which does n't seem wise.I 've found this article ...
< header class= '' Component-header '' > < ! -- Some content here is always the same -- > < ! -- And some content is different for each use -- > < /header > < div class= '' Component-body '' > < ! -- Some content here is always the same -- > < ! -- And some content is different for each use -- > < /div > < footer class...
How can I abstract this repeating pattern in ASP.NET MVC 5 ?
C#
I get an exception System.ArrayTypeMismatchException : Source array type can not be assigned to destination array type for this code snippet : Then I resort to Jon 's answer in Why does `` int [ ] is uint [ ] == true '' in C # , it told me that because of GetArray ( ) returns an Array , the conversion was postponed in ...
var uints = GetArray ( ) ; if ( uints is int [ ] ) { var list = ( ( int [ ] ) uints ) .ToList ( ) ; // fails when call ToList ( ) } private Array GetArray ( ) { var result = new uint [ ] { uint.MaxValue , 2 , 3 , 4 , 5 } ; return result ; } foreach ( var i in ( ( int [ ] ) units ) ) { System.Console.WriteLine ( i.GetTy...
Exception for calling ToList ( ) after conversion from uint [ ] to int [ ] in C #
C#
I ran across this issue today and I 'm not understanding what 's going on : Output : I know Cast ( ) is going to result in deferred execution , but it looks like casting it to IEnumerable results in the deferred execution getting lost , and only if the actual implementing collection is an array.Why is the enumeration o...
enum Foo { Zero , One , Two } void Main ( ) { IEnumerable < Foo > a = new Foo [ ] { Foo.Zero , Foo.One , Foo.Two } ; IEnumerable < Foo > b = a.ToList ( ) ; PrintGeneric ( a.Cast < int > ( ) ) ; PrintGeneric ( b.Cast < int > ( ) ) ; Print ( a.Cast < int > ( ) ) ; Print ( b.Cast < int > ( ) ) ; } public static void Print...
Why Does an Array Cast as IEnumerable Ignore Deferred Execution ?
C#
I do n't understand why the following compiles : My knowledge says that a is assignable to b only if a is of type b or a extends/implements b . But looking at the docs it does n't look like StringValues extends string ( string is a sealed class , therefore it should n't be even possible ) .So I assume this is some impl...
StringValues sv = httpContext.Request.Query [ `` param '' ] ; string s = sv ;
Why is StringValues assignable to String
C#
In C # I am working with large arrays of value types . I want to be able to cast arrays of compatible value types , for example : I want bitmap2 to share memory with bitmap1 ( they have the same bit representations ) . I do n't want to make a copy.Is there a way to do it ?
struct Color { public byte R , G , B , A ; } Color [ ] bitmap1 = ... ; uint [ ] bitmap2 = MagicCast ( bitmap1 ) ;
Casting of arrays in C #
C#
The following code is illegal : The way things should be done is obviously : But the following is also allowed ( I did n't know this and stumbled upon it by accident ) : I guess the compiler verifies that all fields of the struct have been initialized and therefore allows this code to compile . Still I find it confusin...
public struct MyStruct { public MyStruct ( int a , int b ) { this.a = a ; this.b = b ; } public int a ; public int b ; } //now I want to cache for whatever reason the default value of MyStructMyStruct defaultValue ; ... if ( foo ! = defaultValue ) //use of unassigned variable ... MyStruct defaultValue = default ( MyStr...
Confused with little used Value Type initialization
C#
I 've read the answers for Class with indexer and property named `` Item '' , but they do not explain why can I have a class with multiple indexers , all of them creating Item property and get_Item/set_Item methods ( of course working well , as they are different overloads ) , but I can not have an explicit Item proper...
namespace Test { class Program { static void Main ( string [ ] args ) { } public int this [ string val ] { get { return 0 ; } set { } } public string this [ int val ] //this is valid { get { return string.Empty ; } set { } } public int Item { get ; set ; } //this is not valid } } Int32 get_Item ( String val ) Void set_...
`` Item '' property along with indexer
C#
Given this example code : Which returns : -1What does the first arrow operator mean ? By specification it does not look like an expression body or a lambda operator.Is there any reference in the C # language specification about this usage ?
enum op { add , remove } Func < op , int > combo ( string head , double tail ) = > ( op op ) = > op == op.add ? Int32.Parse ( head ) + Convert.ToInt32 ( tail ) : Int32.Parse ( head ) - Convert.ToInt32 ( tail ) ; Console.WriteLine ( combo ( `` 1 '' , 2.5 ) ( op.remove ) ) ;
What does the first arrow operator in this Func < T , TReturn > mean ?
C#
In Haskell , we have the filterM function . The source code for it is : Translating from do notation : To the best of my understanding , > > = on lists in Haskell and SelectMany on IEnumerablein C # are the same operation and so , this code should work just fine : But it does n't work . Can anyone point me to what 's w...
filterM : : ( Monad m ) = > ( a - > m Bool ) - > [ a ] - > m [ a ] filterM _ [ ] = return [ ] filterM p ( x : xs ) = doflg < - p xys < - filterM p xsreturn ( if flg then x : ys else ys ) filterM : : ( Monad m ) = > ( a - > m Bool ) - > [ a ] - > m [ a ] filterM _ [ ] = return [ ] filterM p ( x : xs ) = p x > > = \flg -...
Monadic Programming in C #
C#
I have just noticed that the following code returns true : I have read the Mathf.Approximately Documentation and it states that : Approximately ( ) compares two floats and returns true if they are within a small value ( Epsilon ) of each other.And Mathf.Epsilon Documentation states that : anyValue + Epsilon = anyValue ...
Mathf.Approximately ( 0.0f , float.Epsilon ) ; // true Mathf.Approximately ( 0.0f , 2.0f * float.Epsilon ) ; // true Mathf.Approximately ( 0.0f , 2.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 3.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 4.0f * float.Epsilon ) ; // trueMathf.Approximately ...
Is Mathf.Approximately ( 0.0f , float.Epsilon ) == true its correct behavior ?
C#
I have a mock being created like this : The intellisense for the Setup method says this : `` Specifies a setup on the mocked type for a call to a void returning method . `` But the mocked method p.GetBytes ( ) does not return void , it returns a byte array . Alternatively another Setup method is defined as Setup < > , ...
var mock = new Mock < IPacket > ( MockBehavior.Strict ) ; mock.Setup ( p = > p.GetBytes ( ) ) .Returns ( new byte [ ] { } ) .Verifiable ( ) ; var mock = new Mock < IPacket > ( MockBehavior.Strict ) ; mock.Setup < byte [ ] > ( p = > p.GetBytes ( ) ) .Returns ( new byte [ ] { } ) .Verifiable ( ) ;
Moq confusion - Setup ( ) v Setup < > ( )
C#
I 'm trying to deserialize a part of a json file that represents this class . where two properties are optional : Text and Parameters . I 'd like them to be populated with default values.The problem is that I can not figure out how to make it work for both of them . If I use the DefaultValueHandling.Populate option the...
public class Command { [ JsonRequired ] public string Name { get ; set ; } [ DefaultValue ( `` Json ! '' ) ] public string Text { get ; set ; } // [ DefaultValue ( typeof ( Dictionary < string , string > ) ) ] public Dictionary < string , string > Parameters { get ; set ; } = new Dictionary < string , string > ( ) ; } ...
How can I populate an optional collection property with a default value ?
C#
I am writing a helper method for conveniently setting the Name of a Thread : It 's working as intended . ReSharper , however , claims that the condition is always false and the corresponding code is heuristically unreachable . That 's wrong . A Thread.Name is always null until a string is assigned.So , why does ReSharp...
public static bool TrySetName ( this Thread thread , string name ) { try { if ( thread.Name == null ) { thread.Name = name ; return true ; } return false ; } catch ( InvalidOperationException ) { return false ; } }
Why does ReSharper think that `` thread.Name == null '' is always false ?
C#
Imagine that I have a several Viewer component that are used for displaying text and they have few modes that user can switch ( different font presets for viewing text/binary/hex ) . What would be the best approach for managing shared objects - for example fonts , find dialog , etc ? I figured that static class with la...
static class ViewerStatic { private static Font monospaceFont ; public static Font MonospaceFont { get { if ( monospaceFont == null ) //TODO read font settings from configuration monospaceFont = new Font ( FontFamily.GenericMonospace , 9 , FontStyle.Bold ) ; return monospaceFont ; } } private static Font sansFont ; pub...
Managing of shared resources between classes ?
C#
When you were a kid , did you ever ask your parents how to spell something and they told you to go look it up ? My first impression was always , `` well if could look it up I wouldnt need help spelling it '' . ( yeah yeah I know phonetics ) ... anyway , I was just looking at some code and I found an example like : I ca...
txtbx.CharacterCasing = ( checkbox.Checked ) ? CharacterCasing.Upper : CharacterCasing.Normal ;
Learning by example - terminology ( ? , : , etc )
C#
I have a problem with some overloaded methods and I will try to give a simple implementation of it.So here is a class contains two methods below : and this my entity : Here is where I 'm utilizing it : The problem is that I just have two methods with same name and different arguments so , based on OOP polymorphism conc...
public class MyRepo < TEntity > { public List < TEntity > GetData ( Expression < Func < TEntity , Boolean > > expression ) { //Do something } public List < TEntity > GetData ( Func < TEntity , Boolean > whereClause ) { //Do something } } public class MyEntity { public int Id { get ; set ; } public string Name { get ; s...
Misunderstanding of .NET on overloaded methods with different parameters ( Call Ambiguous )
C#
I have an optimization problem where I have 5 variables : A , B1 , B2 , C1 , C2 . I am trying to optimize these 5 variables to get the smallest root sum square value I can . I have a few optimization techniques that are working ok , but this one in particular is giving me some trouble.I want to explore all 32 options o...
A +/ \- B1 B1 +/\- +/\- B2 B2 B2 B2 //Settign all possible solutions to be iterated through later.double [ ] levelA = new double [ 2 ] ; double [ ] levelB = new double [ 2 ] ; double [ ] levelC = new double [ 2 ] ; double [ ] levelD = new double [ 2 ] ; double [ ] levelE = new double [ 2 ] ; levelA [ 0 ] = a + incA ; l...
How do I iterate between 32 binary options ?
C#
During an research the purpose of this reassignment possibility with structs I ran into following puzzle : Why it is needed to do this = default ( ... ) at the beginning of some struct constructor . It 's actually zeroes already zeroed memory , is n't it ? See an example from .NET core :
public CancellationToken ( bool canceled ) { this = default ( CancellationToken ) ; if ( canceled ) { this.m_source = CancellationTokenSource.InternalGetStaticSource ( canceled ) ; } }
What the purpose of this = default ( ... ) in struct constructor ?
C#
I understand that the following C # code : compiles to : But what does it mean that it compiles to that ? I was under the impression that C # code compiles directly into CIL ?
var evens = from n in nums where n % 2 == 0 select n ; var evens = nums.Where ( n = > n % 2 == 0 ) ;
C # Compiled to CIL
C#
Here is the code extracted of the SingleOrDefault function : I 'm wondering to know if there is any reason why after finding more than one element in the loop , there is no break statement to prevent looping the rest of the list . In anyways , an error will occurs . For a big list where more than one item is found at t...
public static TSource SingleOrDefault < TSource > ( this IEnumerable < TSource > source , Func < TSource , bool > predicate ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; if ( predicate == null ) throw Error.ArgumentNull ( `` predicate '' ) ; TSource result = default ( TSource ) ; long count = 0 ...
Optimization in the SingleOrDefault function of Linq
C#
Just out of curiosity , why does the compiler treat an unconstrained generic type any differently than it would typeof ( object ) ? In the above , casting `` T thing '' to Bar results in a compiler error . Casting `` object thing '' to Bar however is something the compiler lets me do , at my own risk of course.What I d...
class Bar { } class Foo { void foo ( object thing ) { ( ( Bar ) thing ) .ToString ( ) ; } } class Foo < T > { void foo ( T thing ) { ( ( Bar ) thing ) .ToString ( ) ; } } ( ( Bar ) ( object ) thing ) .ToString ( ) ;
The rules of generics and type constraints
C#
I have a question regarding await/async and using async methods in slightly different scenarios than expected , for example not directly awaiting them . For example , Lets say I have two routines I need to complete in parallel where both are async methods ( they have awaits inside ) . I am using await TAsk.WhenAll ( .....
await Task.WhenAll ( new Task [ ] { Task.Run ( async ( ) = > await internalLoadAllEmailTargets ( ) ) , Task.Run ( async ( ) = > await internalEnumerateInvoices ( ) ) } ) ; // this does n't seem to work ok await Task.WhenAll ( new Task [ ] { internalLoadAllEmailTargets ( ) , internalEnumerateInvoices ( ) } ) ;
await/async and going outside the box
C#
I have the following enum defined . I have used underscores as this enum is used in logging and i do n't want to incur the overhead of reflection by using custom attribute.We use very heavy logging . Now requirement is to change `` LoginFailed_InvalidAttempt1 '' to `` LoginFailed Attempt1 '' . If i change this enum , i...
public enum ActionType { None , Created , Modified , Activated , Inactivated , Deleted , Login , Logout , ChangePassword , ResetPassword , InvalidPassword , LoginFailed_LockedAccount , LoginFailed_InActiveAccount , LoginFailed_ExpiredAccount , ForgotPassword , LoginFailed_LockedAccount_InvalidAttempts , LoginFailed_Inv...
How to change enum definition without impacting clients using it in C #
C#
I am looking to setup something very similar to transaction scope which creates a version on a service and will delete/commit at the end of scope . Every SQL statement ran inside the transaction scope internally looks at some connection pool / transaction storage to determine if its in the scope and reacts appropriatel...
public sealed class VersionScope : IDisposable { private readonly GeodatabaseVersion _version ; private readonly VersionManager _versionManager ; public VersionScope ( Configuration config ) { _versionManager = new VersionManager ( config ) ; _version = _versionManager.GenerateTempVersion ( ) ; _versionManager.Create (...
Transaction scope similar functionality
C#
I get a red line under my await in my code saying : The type arguments for method 'TaskAwaiter < TResult > System.WindowsRuntimeSystemExtensions.GetAwaiter < TResult > ( this Windows.Foundation.IAsyncOperation 1 ) ' can not be inferred from the usage . Try specifying the type arguments explicitlyThough the code compile...
private async void Init ( ) { var settings = new I2cConnectionSettings ( I2CAddress ) ; settings.BusSpeed = I2cBusSpeed.StandardMode ; var aqs = I2cDevice.GetDeviceSelector ( I2CControllerName ) ; var dis = await DeviceInformation.FindAllAsync ( aqs ) ; _device = await I2cDevice.FromIdAsync ( dis [ 0 ] .Id , settings )...
TaskAwaiter can not be inferred from the usage
C#
I have an Azure Function with a service bus trigger : In 99.9 % of the invocations , the trigger successfully resolves to a subscription on Azure Service Bus . But sometimes , I see the following error in my log : It seems that the service bus trigger can not resolve the connection variable from settings.I tried to add...
public static async Task Run ( [ ServiceBusTrigger ( `` % inputTopicName % '' , `` % subscriptionName % '' , AccessRights.Manage , Connection = `` connection '' ) ] string mySbMsg ) Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function : UptimeChecker -- - > System.ArgumentExcept...
Connection string is sometimes not available in ServiceBusTrigger
C#
Why can´t we raise an event with a custom implementation , while it is possible without them ? See this code : You see both events are declared within my class . While target.AnotherEvent ( ... ) compiles just fine , target.MyEvent ( ... ) does not : The Event MyEvent can only appear on the left hand side of += or -=.I...
public class Program { private EventHandler myEvent ; public event EventHandler MyEvent { add { myEvent += value ; } remove { myEvent -= value ; } } public event EventHandler AnotherEvent ; public static void Main ( ) { var target = new Program ( ) ; target.MyEvent ( null , null ) ; // ERROR CS0079 target.AnotherEvent ...
Why can´t we raise event with accessors ?
C#
I 'm having hard time understanding the following C # code . This code was taken from Pro ASP.NET MVC 2 Framework by Steven Sanderson . The code esentially creates URLs based on a list of categories . Here 's the code : A lot of stuff is going on here . I 'm guessing it 's defining a function that expects two parameter...
Func < string , NavLink > makeLink = categoryName = > new NavLink { Text = categoryName ? ? `` Home '' , RouteValues = new RouteValueDictionary ( new { controller = `` Products '' , action = `` List '' , category = categoryName , page = 1 } ) , IsSelected = ( categoryName == currentCategory ) // Place home link on top ...
Why did they use this C # syntax to create a list of links in ASP.NET MVC 2 ?
C#
I have following code : and use it as following : Is there any way to define something like this : I used Expression < Func < T , bool > > to use it as where clause in my linq to entities query ( EF code first ) .
public class MyClass < T > { Expression < Func < T , bool > > Criteria { get ; set ; } } public class Customer { //.. public string Name { get ; set ; } } var c = new MyClass < Customer > ( ) ; c.Criteria = x.Name.StartWith ( `` SomeTexts '' ) ; ? p = x= > x.Customer.Name ; var c = new MyClass < Customer > ( ) ; c.Crit...
Define part of an Expression as a variable in c #
C#
Can a static function in a static class which uses yield return to return an IEnumerable safely be called from multiple threads ? Will each thread that calls this always receive a reference to each object in the collection ? In my situation listOfFooClassWrappers is written to once at the beginning of the program , so ...
public static IEnumerable < FooClass > FooClassObjects ( ) { foreach ( FooClassWrapper obj in listOfFooClassWrappers ) { yield return obj.fooClassInst ; } }
Is yield return reentrant ?
C#
Recently I decided to investigate the degree of randomness of a globally unique identifier generated with the Guid.NewGuid method ( which is also the scope of this question ) . I documented myself about pseudorandom numbers , pseudorandomness and I was dazzled to find out that there are even random numbers generated by...
class Program { static char [ ] digitsChar = `` 0123456789 '' .ToCharArray ( ) ; static decimal expectedOccurrence = ( 10M * 100 / 16 ) * 31 / 32 + ( 100M / 32 ) ; static void Main ( string [ ] args ) { for ( int i = 1 ; i < = 10 ; i++ ) { CalculateOccurrence ( i ) ; } } private static void CalculateOccurrence ( int co...
Estimating the digits occurrence probability inside a GUID
C#
i 'm trying to print `` p '' to the screen every second.when I run this : it does n't print at all.But when I run this : Its printing without waiting at all . Can somebody please explain this to me and suggest a fix ?
while ( true ) Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` p '' ) ; while ( true ) Console.WriteLine ( `` p '' ) ; Thread.Sleep ( 1000 ) ;
waiting for a second every time in a loop in c # using Thread.Sleep
C#
I have been playing with WPF for a while and I came across an interesting thing . When I bind DateTime object to the Label 's content then I see locally formatted representation of the date . However , when I bind to the TextBlock 's Text property then I actually see English one.It seems that TextBlock is using some so...
// MainWindow.xaml < Window x : Class= '' BindConversion.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlfor...
Culture difference between Label and TextBlock
C#
I have a method I used in MvvmCross 4.x that was used with the NotificationCompat.Builder to set a PendingIntent of a notification to display a ViewModel when the notification is clicked by the user . I 'm trying to convert this method to use the MvvmCross 5.x IMvxNavigationService but ca n't see how to setup the prese...
private PendingIntent RouteNotificationViewModelPendingIntent ( int controlNumber , RouteNotificationContext notificationContext , string stopType ) { var request = MvxViewModelRequest < RouteNotificationViewModel > .GetDefaultRequest ( ) ; request.ParameterValues = new Dictionary < string , string > { { `` controlNumb...
How do I get PendingIntent using the MvvmCross 5 IMvxNavigationService ?
C#
I 'm making a jquery clone for C # . Right now I 've got it set up so that every method is an extension method on IEnumerable < HtmlNode > so it works well with existing projects that are already using HtmlAgilityPack . I thought I could get away without preserving state ... however , then I noticed jQuery has two meth...
$ ( 'ul.first ' ) .find ( '.foo ' ) .css ( 'background-color ' , 'red ' ) .end ( ) .find ( '.bar ' ) .css ( 'background-color ' , 'green ' ) .end ( ) ;
How to design my C # jQuery API such that it is n't confusing to use ?
C#
I 'm quite new to Linq . I have something like this : This works fine but for obvious reasons I do n't want the split ( ) method to be called twice.How can I do that ? Thanks for all your responses : ) , but I can only choose one .
dict = fullGatewayResponse.Split ( ' , ' ) .ToDictionary ( key = > key.Split ( '= ' ) [ 0 ] , value = > value.Split ( '= ' ) [ 1 ] )
Linq call a function only once in one statement
C#
Let 's say there are these generic types in C # : and these concrete types : Now the definition of PersonRepository is redundant : the fact that the KeyType of Person is int is stated explicitly , although it can be deduced from the fact that Person is a subtype of Entity < int > .It would be nice to be able to define ...
class Entity < KeyType > { public KeyType Id { get ; private set ; } ... } interface IRepository < KeyType , EntityType > where EntityType : Entity < KeyType > { EntityType Get ( KeyType id ) ; ... } class Person : Entity < int > { ... } interface IPersonRepository : IRepository < int , Person > { ... } interface IPers...
Generic Type Inference in C #
C#
I have the following sample code.According to MSDN : Exists property : true if the file or directory exists ; otherwise , false.Why Exists returns false after directory has been created ? Am I missing something ?
private DirectoryInfo PathDirectoryInfo { get { if ( _directoryInfo == null ) { // Some logic to create the path // var path = ... _directoryInfo = new DirectoryInfo ( path ) ; } return _directoryInfo ; } } public voide SaveFile ( string filename ) { if ( ! PathDirectoryInfo.Exists ) { PathDirectoryInfo.Create ( ) ; } ...
Creating Directory does n't update the Exists property to true
C#
This is mostly academic - but I was looking at the implementation of Equals ( ) for ValueTypes . The source code is here : http : //referencesource.microsoft.com/ # mscorlib/system/valuetype.cs # 38The code that caught my eye was this : FastEqualsCheck ( ) is declared as follows : My understanding is that the ' [ Metho...
// if there are no GC references in this object we can avoid reflection // and do a fast memcmp if ( CanCompareBits ( this ) ) return FastEqualsCheck ( thisObj , obj ) ; [ System.Security.SecuritySafeCritical ] [ ResourceExposure ( ResourceScope.None ) ] [ MethodImplAttribute ( MethodImplOptions.InternalCall ) ] privat...
How Can I Call FastEqualsCheck ( ) ?
C#
I wanted to add a nice shadow to my borderless form , and the best way I found to do it with minimal performance loss is to use DwmExtendFrameIntoClientArea . However , this seems to be causing Windows to draw a classic title bar over the window , but it is non-functional ( ie . the glitch is merely graphical ) .This i...
int v = ( int ) DWMNCRENDERINGPOLICY.DWMNCRP_ENABLED ; NativeApi.DwmSetWindowAttribute ( Handle , DwmWindowAttribute.NCRENDERING_POLICY , ref v , sizeof ( int ) ) ; int enable = 0 ; NativeApi.DwmSetWindowAttribute ( Handle , DwmWindowAttribute.ALLOW_NCPAINT , ref enable , sizeof ( int ) ) ; MARGINS margins = new MARGIN...
Prevent Win32 from drawing classic title bar
C#
I find myself creating loads of the properties following the pattern : Is there an easy way to automate creating of these properties ? Usually I : type the field , including the readonly keywordSelect `` initialize from constructor parametersSelect `` encapsulate '' Is it possible to make it quicker ?
private readonly MyType sth ; public MyClass ( MyType sth ) //class constructor { this.sth = sth ; } public MyType Sth { get { return sth ; } }
How can I automate creating immutable properties with ReSharper ?
C#
I just came across this weird 'behavior ' of the Garbage Collector concerning System.Threading.ThreadLocal < T > that I ca n't explain . In normal circumstances , ThreadLocal < T > instances will be garbage collected when they go out of scope , even if they are n't disposed properly , except in the situation where they...
public class Program { public class B { public A A ; } public class A { public ThreadLocal < B > LocalB ; } private static List < WeakReference > references = new List < WeakReference > ( ) ; static void Main ( string [ ] args ) { for ( var i = 0 ; i < 1000 ; i++ ) CreateGraph ( ) ; GC.Collect ( ) ; GC.WaitForPendingFi...
Memory leak when ThreadLocal < T > is used in cyclic graph
C#
I know there 's a couple similarly worded questions on SO about permutation listing , but they do n't seem to be quite addressing really what I 'm looking for . I know there 's a way to do this but I 'm drawing a blank . I have a flat file that resembles this format : Now here 's the trick : I want to create a list of ...
Col1|Col2|Col3|Col4|Col5|Col6a|b , c , d|e|f|g , h|i . . . IEnumerable < string > row = new string [ ] { `` a '' , `` b , c , d '' , `` e '' , `` f '' , `` g , h '' , `` i '' } ; IEnumerable < string > permutations = GetPermutations ( row , delimiter : `` / '' ) ; a/b/e/f/g/ia/b/e/f/h/ia/c/e/f/g/ia/c/e/f/h/ia/d/e/f/g/i...
Split and join multiple logical `` branches '' of string data
C#
To declare float numbers we need to put ' f ' for floats and 'd ' for doubles . Example : It is said that C # defaults to double if a floating point literal is omitted.My question , is what prevents a modern language like ' C # ' to 'DEFAULTS ' to the left hand side variable type ? After all , the compiler can see the ...
float num1 = 1.23f ; // float stored as floatfloat num2 = 1.23 ; // double stored as float . The code wo n't compile in C # .
C # floating point literals : Why compiler does not DEFAULTS to the left hand side variable type
C#
I was doing a refactoring of class and thought of moving 100 lines in a separate method . Like this : At calling method of Compiler throws exception : Readonly local variable can not be used as an assignment target for doc and mem.Edit : here only i adding content in pdf document in another method . so i need to pass s...
using iTextSharp.text ; using iTextSharp.text.pdf ; class Program { private static void Main ( string [ ] args ) { Document doc = new Document ( iTextSharp.text.PageSize.LETTER , 10 , 10 , 42 , 35 ) ; using ( var mem = new MemoryStream ( ) ) { using ( PdfWriter wri = PdfWriter.GetInstance ( doc , mem ) ) { doc.Open ( )...
IDisposable objects as ref param to method
C#
Very short question but I could n't find a solution on the web right now.Will 1 + 2 be performed during run- or compile-time ? Reason for asking : I think most people sometimes use a literal without specifying why it has been used or what it means because they do not want to waste a bit performance by running the calcu...
int test = 1 + 2 ; int nbr = 31536000 ; //What the heck is that ? int nbr = 365 * 24 * 60 * 60 ; //I guess you know what nbr is supposed to be now ...
Are arithmetic operations on literals in C # evaluated at compile time ?
C#
I have a WPF application with a number of comboboxes that tie together . When I switch comboboxx # 1 , combobox # 2 switches , etc.Here is the xaml for the 2 comboboxes : CboDivision gets populated at the beginning and doesnt need a reset . HEre is the code that calls the change in division , which should trigger a cha...
< ComboBox Grid.Row= '' 1 '' Height= '' 23 '' HorizontalAlignment= '' Right '' Margin= '' 0,12,286,0 '' ItemsSource= '' { Binding } '' Name= '' CboDivision '' VerticalAlignment= '' Top '' Width= '' 120 '' SelectionChanged= '' CboDivision_SelectionChanged '' / > < ComboBox Height= '' 23 '' HorizontalAlignment= '' Right ...
Clearing and refilling a bound combo box
C#
The Stackoverflow API is returning an unexpected response when C # to create a HTTP GET request.If I paste http : //api.stackoverflow.com/1.1/users/882993 into the browsers address bar I get the correct JSON response : If I attempt to perform the same action in code : I get the response :
{ `` total '' : 1 , `` page '' : 1 , `` pagesize '' : 30 , `` users '' : [ { `` user_id '' : 882993 , `` user_type '' : `` registered '' , `` creation_date '' : 1312739131 , `` display_name '' : `` Jack '' , `` reputation '' : 1926 , `` email_hash '' : `` 69243d90e50d9e0b3e025517fd23d1da '' , `` age '' : 23 , `` last_a...
Stackoverflow API response format
C#
Why does the OR operator in vb and C # give different results.http : //dotnetfiddle.net/wC9AgGhttp : //dotnetfiddle.net/g4tLQ9
Console.WriteLine ( 0x2 | 0x80000000 ) ; output 2147483650 Console.WriteLine ( & H2 Or & H80000000 ) output -2147483646
C # vs VB.NET bitwise OR
C#
There 's far too much code to paste into a question here so I have linked to a public gist.https : //gist.github.com/JimBobSquarePants/cac72c4e7d9f05f13ac9I have an animated gif encoder as part of an image library that I maintain and there is something wrong with it.If I attempt to upload any gif that have been output ...
unknown block type 0 at *different position each time*
Animated gif encoder error
C#
Given the output of query : What would you consider the neatest way to detect if a file is in the queryResult ? Here is my lame try with LINQ : There must be an more elegant way to figure out the result .
var queryResult = from o in objects where ... select new { FileName = o.File , Size = o.Size } string searchedFileName = `` hello.txt '' ; var hitlist = from file in queryResult where file.FileName == searchedFileName select file ; var contains = hitlist.Count ( ) > 0 ;
Writing 'CONTAINS ' query using LINQ
C#
According to the Constraints on Type Parameters ( C # Programming Guide ) documentation it says , and I quote : When applying the where T : class constraint , avoid the == and ! = operators on the type parameter because these operators will test for reference identity only , not for value equality . This is the case ev...
public static void OpTest < T > ( T s , T t ) where T : class { System.Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` target '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( `` target '' ) ; string s2 = sb.ToString ( ) ; OpTest < string > ( s1 , s2 ) ; } public Node ( T type ,...
Avoid == and ! = operators on generic type parameters , but can it compare with null ?
C#
I have this simple code : This interface should be covariant on T , and i 'm using it this way : Note the constraint for T to implement IComposite.The synchronization method takes an IReader < IComposite > in input : The compiler tells me it can not convert from IReader < T > to IReader < IComposite > despite the const...
public interface IReader < out T > { IEnumerable < T > GetData ( ) ; } private static Func < bool > MakeSynchroFunc < T > ( IReader < T > reader ) where T : IComposite { return ( ) = > Synchronize ( reader ) ; } private static bool Synchronize ( IReader < IComposite > reader ) { // ... ... }
.NET Covariance
C#
I happen to see a code something like this.When and why do we need this kind of dynamic type casting for parameters ?
function ( ( dynamic ) param1 , param2 ) ;
dynamic type casting in parameter in c #
C#
Sometimes I want to add more typesafety around raw doubles . One idea that comes up a lot would be adding unit information with the types . For example , In the case like above , where there is only a single field , will the JIT be able to optimize away this abstraction in all cases ? What situations , if any , will re...
struct AngleRadians { public readonly double Value ; /* Constructor , casting operator to AngleDegrees , etc omitted for brevity ... */ } // 1 . Is the value-copy constructor zero cost ? // Is ... var angleRadians = new AngleRadians ( myDouble ) ; // The same as ... var myDouble2 = myDouble ; // 2 . Is field access zer...
Is a struct wrapping a primitive value type a zero cost abstraction in C # ?
C#
Basically , I have keywords like sin ( and cos ( in a textbox , which I want to have behave like a single character.When I mention the entire string below it is referring to the group of characters ( for example `` sin ( `` ) Using sin ( as an example : If the caret was in this position ( behind the s ) : If you presse...
# region Rightcase Keys.Right : { s = txt.Substring ( caretLocation ) ; foreach ( string combo in charCombinations ) { if ( s.StartsWith ( combo ) ) { textBox1.SelectionStart = caretLocation + combo.Length - 1 ; break ; } } break ; } # endregion # region Leftcase Keys.Left : { s = txt.Substring ( 0 , caretLocation ) ; ...
C # Make a group of characters in a textbox behave like one character
C#
When using C # Strongnames on DLLs and using the InternalsVisibleTo tags andwhen the public key uses SHA256 ( or SHA512 ) We 're noticing that the compile process fails as if the InternalsVisibleTo tags were never even declared . The error we get is MyInternalClass is inaccessible due to its protection level < snip > W...
sn -k 4096 SignKey.snksn -p SignKey.snk SignKeyPublic.snk sha256sn -tp SignKeyPublic.snk [ assembly : InternalsVisibleTo ( `` MyProjectTest , PublicKey=LongPublicKeyHere '' ) ]
StrongNaming with InternalsVisibleTo tag fails when SHA256 used
C#
I have a frustrating problem with a bit of code and do n't know why this problem occurs . When running without Code optimization then the result is as expected . _cursorLeft and left as far as _cursorTop and top are equal.But when I run it with Code optimization both values _cursorLeft and _cursorTop become bizzare : I...
//// .NET FRAMEWORK v4.6.2 Console Appstatic void Main ( string [ ] args ) { var list = new List < string > { `` aa '' , `` bbb '' , `` cccccc '' , `` dddddddd '' , `` eeeeeeeeeeeeeeee '' , `` fffff '' , `` gg '' } ; foreach ( var item in list ) { Progress ( item ) ; } } private static int _cursorLeft = -1 ; private st...
C # Code optimization causes problems with Interlocked.Exchange ( )