lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | This is best illustrated with an example.Say I want to load several records from a database at the beginning of a web request . I want to pull in all the necessary data asynchronously . I might have something like this : Now let ’ s say I want to load this data in parallel . Suddenly this nice clear/clean async code be... | var user = await Database.GetUser ( userId ) ; var group = await Database.GetGroup ( groupId ) ; var members = await Database.GetGroupMembers ( groupId ) ; var userTask = Database.GetUser ( userId ) ; var groupTask = Database.GetGroup ( groupId ) ; var membersTask = Database.GetGroupMembers ( groupId ) ; await Task.Whe... | What is the most elegant way to load multiple variables asynchronously in parallel in c # |
C# | I was trying around a bit with Try Roslyn when I entered this piece of code : And it gave me back this code : What I do n't get is why it would do the assignment of the backing field twice inside of the constructor : Is this an error of the website or does the Roslyn compiler actually do this ( would be really dumb imo... | using System ; using System.Linq ; using System.Collections.Generic ; using Microsoft.CSharp ; public class C { public C ( ) { x = 4 ; } public int x { get ; } = 5 ; } using System ; using System.Diagnostics ; using System.Reflection ; using System.Runtime.CompilerServices ; using System.Security ; using System.Securit... | Why does the IL set this value twice ? |
C# | I am working on a web application . I have two text boxes , one is txtEmployeeID , and one is txtEmployeeName . What I am trying to do here is when the user enter EmployeeID in the txtEmployeeID , the name of the employee will show up in the txtEmployeeName . I got this part working so far . However , if the employeeID... | EmployeeID EmployeeName00000345 James Murray Employee ID : 345 Employee Name : James Murray @ Employee_ID varchar ( 8 ) = NULLSELECT s.Employee_ID , p.FIRST_NAME , p.LAST_NAME FROM [ dbo ] . [ Employee ] e INNER JOIN [ dbo ] . [ Person ] p ON e.PERSON_ID = p.PERSON_ID WHERE p.Employee_ID = @ Employee_ID | How to ignore integer start with 0 |
C# | Author post-edit : Chosen solution ( Original question remains below this box ) SUMMARY : You SHOULD NOT name a class the same as its namespace . Therefore should a product name be used for the namespace or the main class ? Chosen solution : I decided to apply the product name to the namespace and add a suffix to the m... | namespace Acme.Web.Foobarinator { public class Foobarinator { } // BAD ! Same name as namespace ! public class FoobarinatorInfo { } public enum Mode { Disabled , Enabled } } namespace Acme.Web { public class Foobarinator { } public class FoobarinatorInfo { } public enum FoobarinatorMode { Disabled , Enabled } // More p... | Product trademark name begs for class/namespace with same name |
C# | Why is it giving me a null in s variable ? I know that casting it using int ? s = ( int ? ) i ; will work fine but why ca n't I use an as operator ? | long ? i = 10000 ; int ? s = i as int ? ; | Why ` as ` is giving null for nullable value types ? |
C# | This question is a slightly modified version of Convert List < T > to Dictionary with strategyI have List < DTO > where DTO class looks like this , I create objects and add it to List.Now my requirement is I need to create a List from the dtoCollection where Name field should be unique across the entire List.For exampl... | private class DTO { public string Name { get ; set ; } public int Count { get ; set ; } } var dto1 = new DTO { Name = `` test '' , Count = 2 } ; var dto2 = new DTO { Name = `` test '' , Count = 3 } ; var dtoCollection = new List < DTO > { dto1 , dto2 } ; | Group a List based on uniqueness |
C# | Hi I have a listbox Whenever a user selects an item a request is sent to the web Now I want to cancel the previous operation when the user selected the item and then start the new operation.I used the following codes to do this , I wanted to know if these codes work well . Or should I try another way ? and i run func t... | private CancellationTokenSource ts = new CancellationTokenSource ( ) ; private async void Subf2mCore ( CancellationToken ct ) { HtmlDocument doc = await web.LoadFromWebAsync ( url ) ; ... foreach ( var node in doc ) { if ( ! ct.IsCancellationRequested ) { ... . } } } ts ? .Cancel ( ) ; ts = new CancellationTokenSource ... | Cancel Task in async void |
C# | Using Visual Studio 2013 , I 'm trying to reproduce the gotcha mentioned in Eric Lippert 's blog post `` Closing over the loop variable considered harmful '' .In the project properties , I selected `` C # 3.0 '' as the language version ( Build > Advanced… ) . Further , I selected `` .NET Framework 3.5 '' as the target ... | using System ; using System.Collections.Generic ; namespace Project1 { class Class1 { public static void Main ( string [ ] args ) { var values = new List < int > ( ) { 100 , 110 , 120 } ; var funcs = new List < Func < int > > ( ) ; foreach ( var v in values ) { funcs.Add ( ( ) = > v ) ; } foreach ( var f in funcs ) Con... | Reproducing the `` close over the variable of a foreach '' gotcha |
C# | Imagine that you have a list called List < Foo > .Foo is an abstract class , so this can be FooA , FooB , FooC or FooD . And I 'd like to have an extension for List < T > where you can order this elements by type but sequently.For example , if I have 9 elements in it.Order by type sequently will be.I 'm trying that the... | FooA , FooA , FooB , FooD , FooC , FooC , FooA , FooB , FooA FooA , FooB , FooC , FooD , FooA , FooB , FooC , FooA , FooA new [ ] { typeof ( FooA ) , typeof ( FooB ) , typeof ( FooC ) , typeof ( FooD ) } | How to order a list by type ? |
C# | This has me pretty stumped . Maybe I 'm too tired right now.inputArea is a nullable Rectangle , which in my particular case is null.The first two statements yields a cropArea initialized to 0 . The second , however , yields the correct cropArea based on the image width and height . Have I misunderstood anything with th... | Rectangle rectangle = new Rectangle ( 0 , 0 , image.Width , image.Height ) ; Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value ; if ( inputArea == null ) cropArea = rectangle ; | Weird behaviour with conditional operator in .Net |
C# | I have the following code : I would like my listSrc result to contain two Info items whose Name and Num properties are : However , the code I show above results in four items : | public class Info { public string Name ; public string Num ; } string s1 = `` a , b '' ; string s2 = `` 1,2 '' ; IEnumerable < Info > InfoSrc = from name in s1.Split ( ' , ' ) from num in s2.Split ( ' , ' ) select new Info ( ) { Name = name , Num = num } ; List < Info > listSrc = InfoSrc.ToList ( ) ; a , 1b , 2 a , 1a ... | Split multiple strings into a list of objects in C # |
C# | Is there a way to reliably get a unique e-mail address from one put in from a user ? The problem is services such as GMail allow you to put a period in the address and it 's stripped out whereas with other services this is not the case.GMail : All of these are the sameOther service : These are unique.Other than having ... | chad.moran @ gmail.comc..hadmoran @ gmail.comc.h.a.d.m.o.r.a.n @ gmail.com chad.moran @ -- -.comc..hadmoran @ -- -.com | How to de-duplicate e-mail addresses |
C# | How can this code : run 3x faster than this code : The first code snippet does exactly the same fast divide operation ( thats the multiply then shift right ) but also a subtraction and multiplication but but the JIT compiler appears to be producing slower code.I have the disassembly code for each available.The slower c... | var check = 0 ; for ( var numerator = 0 ; numerator < = maxNumerator ; numerator++ ) { check += numerator > = 0 ? numerator - ( int ) ( ( numerator * qdi.Multiplier ) > > qdi.Shift ) * qdi.Number : numerator - ( int ) - ( ( -numerator * qdi.Multiplier ) > > qdi.Shift ) * qdi.Number ; } return check ; var check = 0 ; fo... | How can the first of these two code snippets run 3x faster than the second when its doing more work ? |
C# | Using interpolated strings to send sql server queries , why with a datacontext on LINQ to SQL you need to add single quotes ? db.ExecuteCommand ( $ '' delete table where date = ' { date : yyyy-MM-dd } ' '' ) ; while with EF Core you need to remove them ? and why in EF Core , if you 're using String.Format instead of in... | db.Database.ExecuteSqlCommand ( $ '' delete table where date = { date : yyyy-MM-dd } '' ) ; String.Format ( `` delete table where date= ' { 0 } ' '' , date.ToString ( `` yyyy-MM-dd '' ) ) ; | Ef Core vs Linq on interpolated string |
C# | So insteed of writing : I thought of writing : It kind of feels wrong , especially this part `` obj.Collection = obj.Collection ... '' What do you guys think ? Regards , | if ( obj.Collection == null ) obj.Collection = new Collection ( ) ; obj.Collection.Add ( something ) ; obj.Collection = obj.Collection ? ? new Collection ; obj.Collection.Add ( something ) ; | What 's wrong with the ? ? operator used like this : |
C# | This code seems to not call the Mixed constructor and prints y = 0However , simply modifying the Main function to look like this results in the constructor being called.This prints : Why does simply adding this reference to a non-static field result in the constructor being called correctly ? Should n't creating the ob... | public class Mixed { public int x ; public static int y ; public Mixed ( ) { x = 1 ; y = 1 ; } } public class Program { static Mixed mixed = new Mixed ( ) ; static void Main ( string [ ] args ) { Console.WriteLine ( `` y = `` + Mixed.y ) ; Console.ReadLine ( ) ; } } static void Main ( string [ ] args ) { Console.WriteL... | Why is n't this C # instance constructor being called , unless there is a reference to a non-static member ? |
C# | I am iterating through a collection in a foreach loop and was wondering.When this gets executed by the .NET runtimeDoes the myDict.Values get invoked for every loop or is it called only once ? Thanks , | foreach ( object obj in myDict.Values ) { // ... do something } | Collections use in foreach loop |
C# | This is best illustrated with an example : I want to tell , for an arbitrary object , if I can cast it to Cat . Sadly I can not seem to use the is/as operator.I 'm hoping to avoid a try/catch ( InvalidCastException ) as I may be doing this a lot and this would be quite expensive.Is there a way to do this cheaply and ea... | class Cat { } class Dog { public static implicit operator Cat ( Dog d ) { return new Cat ( ) ; } } void Main ( ) { var d = new Dog ( ) ; if ( d is Cat ) throw new Exception ( `` d is Cat '' ) ; var c1 = ( Cat ) d ; // yes //var c2 = d as Cat ; // Wo n't compile : Can not convert type 'Dog ' to 'Cat ' via a reference co... | Is there a `` cheap and easy '' way to tell if an object implements an explicit/implicit cast operator to a particular type ? |
C# | Here is the codeI can´t get the limit counter to increment for each timeI can get it to count to 1 between each outputline , but that´s itAny idea why ? I want it to be able to count every `` overshoot '' | class Actuator { private int limit_count = 0 ; public int Inc_Limit_counter ( int temp , int co2_conc , int rel_humid ) { if ( temp > 70 || co2_conc > 450 || rel_humid > 77 ) limit_count++ ; //Console.WriteLine ( `` test { 0 } '' , limit_count ) ; return limit_count ; } public int Get_limit_count ( ) { return limit_cou... | Displaying values from a private int in c # |
C# | UPDATE : The following code only makes sense in C # 4.0 ( Visual Studio 2010 ) It seems like I am having some misunderstanding of covariance/contravariance thing . Can anybody tell me why the following code does n't compile ? while this one compiles : ( ! ! ! ) | public class TestOne < TBase > { public IEnumerable < TBase > Method < TDerived > ( IEnumerable < TDerived > values ) where TDerived : TBase { return values ; } } public interface IBase { } public interface IDerived : IBase { } public class TestTwo { public IEnumerable < IBase > Method ( IEnumerable < IDerived > values... | Covariance/contravariance : how to make the following code compile |
C# | In specific , if I say : How does the compiler go about generating a concrete enumerable class out of this ? | public static IEnumerable < String > Data ( ) { String connectionString = `` ... '' ; using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; IDataReader reader = new SqlCommand ( `` '' , connection ) .ExecuteReader ( ) ; while ( reader.Read ( ) ) yield return String.Format (... | How does the compiler use 'yield return ' to build a class |
C# | I am making a horse programme . I have the horse face and wish to apply a bit mask . Only the horses eyes should be visible when it is wearing the bit mask . First I must convert the horses face to digital . For this I have a set of bits which include 0 , 0 , 0 , and 1 for the face of the horse.I am using C # and have ... | //the head of the horsestring head = `` # # '' + `` # # # # # # # # '' + `` # O O # '' + `` # # '' + `` # # '' + `` # = = # '' + `` # ==== # `` + `` # # # # `` ; //digitize the horse into bits of binarystring binaryHead = head.Replace ( ' # ' , ' 0 ' ) .Replace ( '= ' , ' 0 ' ) .Replace ( ' ' , ' 0 ' ) .Replace ( ' O '... | Can not apply bit mask |
C# | I 've written a recursive function which yields IEnumerable < int > So If I write It should yield But it does n't work as expected . ( it displays 0 ) .In normal recursive function ( which return int - without Ienumerable ) it works fine.Question : How can I fix the code so it yields the expected value ? nb . No there ... | IEnumerable < int > Go ( int b ) { if ( b==0 ) yield return 0 ; else foreach ( var element in Go ( b-1 ) ) { yield return element ; } } foreach ( var element in Go ( 3 ) ) { Console.WriteLine ( element ) ; } 0123 | Recursive IEnumerable does n't work as expected ? |
C# | I am trying to upgrade my project from Microsoft.WindowsAzure.Storage v9 ( deprecated ) to latest sdk Azure.Storage.Blobs v12.My issue ( post-upgrade ) is accessing the ContentHash property.Pre-upgrade steps : upload file to blobget MD5 hash of uploaded file provided by CloudBlob.Properties.ContentMD5 from Microsoft.Wi... | CloudBlobClient cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient ( ) ; cloudBlobClient.DefaultRequestOptions.StoreBlobContentMD5 = true ; var container = _blobServiceClient.GetBlobContainerClient ( containerName ) ; var blob = container.GetBlobClient ( blobPath ) ; BlobHttpHeaders blobHttpHeaders = null ; i... | ContentHash is null in Azure.Storage.Blobs v12.x.x |
C# | When trying to compile the following code in LINQPad : I get the following error : The type arguments for method 'System.Linq.Enumerable.Select ( System.Collections.Generic.IEnumerable , System.Func ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.If I use a lambda like d = > GetPro... | void Main ( ) { DriveInfo.GetDrives ( ) .Select ( GetProviderName ) .Dump ( ) ; } static string GetProviderName ( DriveInfo drive ) { // some irrelevant WMI code ... } | Why generic type inference does n't work in that case ? |
C# | In my viewmodel , I have a list of items I fetch from the database and then send to the view . I would like to know if it 's possible to avoid having to refill the options property whenever I hit a Post action and need to return the model ( for validation errors and what not ) ? In webforms , this would n't be necessar... | public class TestModel { public TestModel ( ) { Departments = new List < SelectListItem > ( ) ; } public string Name { get ; set ; } public int Department { get ; set ; } public IEnumerable < SelectListItem > Departments { get ; set ; } } @ model MvcApplication1.Models.TestModel @ using ( Html.BeginForm ( ) ) { @ Html.... | Reuse model data in a post action |
C# | I have created a bezier curve by adding the following script to an empty game object in the inspector . This draws to complete curve at once when I run the code . How can I animate it over a given period of time , say 2 or 3 seconds ? | public class BCurve : MonoBehaviour { LineRenderer lineRenderer ; public Vector3 point0 , point1 , point2 ; int numPoints = 50 ; Vector3 [ ] positions = new Vector3 [ 50 ] ; // Use this for initializationvoid Start ( ) { lineRenderer = gameObject.AddComponent < LineRenderer > ( ) ; lineRenderer.material = new Material ... | How to animate a bezier curve over a given duration |
C# | This is my first question on Stack Overflow . Apologies in advance if I do n't do things quite right while I 'm learning how things work here.Here is my code : It produces this XML : I do n't understand why I am not getting < Items testAttribute= '' foo '' > Please can anyone tell me what I need to add to my code so th... | public void TestSerialize ( ) { ShoppingBag _shoppingBag = new ShoppingBag ( ) ; Fruits _fruits = new Fruits ( ) ; _fruits.testAttribute = `` foo '' ; Fruit [ ] fruit = new Fruit [ 2 ] ; fruit [ 0 ] = new Fruit ( `` pineapple '' ) ; fruit [ 1 ] = new Fruit ( `` kiwi '' ) ; _fruits.AddRange ( fruit ) ; _shoppingBag.Item... | C # XML Serializer wo n't store an attribute |
C# | I 'm having a hard time getting the LINQ-syntax.. How can I do this command in a better way ? As you can see , there 's a table user , a table pintouser and a table pin . Pintouser references user and pin . Is it possible to write something short like `` user.pintouser.pin '' ? I think I have the navigation properties ... | var user = ( from u in context.users where u.email.Equals ( email ) select u ) .Single ( ) ; var pinToUser = ( from ptu in context.pintousers where ptu.user_id.Equals ( user.id ) select ptu ) .Single ( ) ; var pin = ( from p in context.pins where p.idpin.Equals ( pinToUser.pin_idpin ) select p ) .Single ( ) ; return pi... | Making a LINQ query better |
C# | I have this code after decompileI do n't know what mean operator/symbol < > before some operations . Does somebody know ? | SampleClass sampleClass ; SampleClass < > g__initLocal0 ; int y ; sampleClass = null ; Label_0018 : try { < > g__initLocal0 = new SampleClass ( ) ; < > g__initLocal0.X = 5 ; < > g__initLocal0.Y = 10 ; sampleClass = < > g__initLocal0 ; goto Label_003A ; } catch ( Exception ) { Label_0035 : goto Label_003A ; } Label_003A... | What does the symbol < > mean in MSIL ? |
C# | Basically I have a few functions that look like this : Under the assumption I can use the same resource instead of a different one [ instance ] in every function is it ok practice in regard to cleanup and such to do this ? : | class MyClass { void foo ( ) { using ( SomeHelper helper = CreateHelper ( ) ) { // Do some stuff with the helper } } void bar ( ) { using ( SomeHelper helper = CreateHelper ( ) ) { // Do some stuff with the helper } } } class MyClass { SomeHelper helper = CreateHelper ( ) ; // ... foo and bar that now just use the clas... | Using statement in every function - > convert to class field with proper cleanup ? |
C# | I have a class hierarchy like thisI wanted to create an action Action lamda that had a generic type paramater of type CalendarEventBase that I could assign to the following different methods : I created the following illegal assignment : The compiler complains that it was expecting a method with void ( CalendarEventBas... | public abstract class CalendarEventBase { } public class TrainingEvent : CalendarEventBase { } public class AuditEvent : CalendarEventBase { } public void EmailCancelation ( TrainingEvent trainingEvent ) public void EmailCancelation ( AuditEvent auditEvent ) Action < CalendarEventBase > emailCancelation = _trainingServ... | Contravariance in Action lambda - C # |
C# | Normally if I would have had this : I would have gotten a CA1062 : Validate arguments of public methods from code analysis . It would have been fixed by modifying the code as such : But now I want to use another means of doing this validation : since the method validates the argument the code analysis rule is satisfied... | public string Foo ( string text ) { return text.Substring ( 3 ) ; } public string Foo ( string text ) { if ( text == null ) throw new ArgumentNullException ( `` text '' ) ; else if ( string.IsNullEmptyOrWhiteSpace ( text ) throw new ArgumentException ( `` May not be empty or white space '' , `` text '' ) else if ( text... | How to let Code Analysis pick up that an argument was validated in called method |
C# | Goal : Generic enumerated type to be the same type when returned.Note : This works when the types are entered but I do n't understand why they ca n't be inferred.List < T > then return List < T > IOrderedEnumerable < T > then return IOrderedEnumerable < T > ETCCurrent method ( works only if all types are entered ) Exam... | public static TEnumerable WithEach < TEnumerable , T > ( this TEnumerable items , Action < T > action ) where TEnumerable : IEnumerable < T > { foreach ( var item in items ) action.Invoke ( item ) ; return items ; } var list = new List < int > ( ) ; //TODO : Mock random valueslist.WithEach ( x = > Console.WriteLine ( x... | How can I return < TEnumerable , T > : where TEnumerable : IEnumerable < T > |
C# | I 'm trying to downcast a controller instance inside an action filter , and I 'm having issue doing so.I have a DefaultController class : IBaseEntity is : I have an instance of a controller , inheriting the DefaultController : Workflow is inheriting BaseEntity which implements IBaseEntity.Now , inside my action filter ... | public abstract partial class DefaultController < T > : Controller where T : IBaseEntity { } public interface IBaseEntity { int Id { get ; set ; } DateTime CreatedOn { get ; set ; } DateTime ModifiedOn { get ; set ; } int CreatedBy { get ; set ; } int ModifiedBy { get ; set ; } int OwnerId { get ; set ; } } public clas... | How to do this tricky down-casting with generic constraints ? |
C# | I 've noticed something very odd when working with addition of nullable floats . Take the following code : result is 6.099999 whereas result2 is 6.1 . I 'm lucky to have stumbled on this at all because if I change the values for a , b , and c the behavior typically appears correct . This may also happen with other arit... | float ? a = 2.1f ; float ? b = 3.8f ; float ? c = 0.2f ; float ? result = ( a == null ? 0 : a ) + ( b == null ? 0 : b ) + ( c == null ? 0 : c ) ; float ? result2 = ( a == null ? 0 : a.Value ) + ( b == null ? 0 : b.Value ) + ( c == null ? 0 : c.Value ) ; | Curious Behavior When Doing Addition on Nullable Floats |
C# | Want to learn how an instance of a class is created in the background . When this statement is evaluated . What will happen in the backgroud ? My following statements are correct or not ( for 32-bit OS machine ) ? A memory space will be created and referenced as myClass ; within above memory space , 4 bytes is used for... | public class MyClass { int i = 0 ; string str = `` here '' ; MyStruct mystruct ; B b ; ArrayList myList = new ArrayList ( 10 ) ; public MyClass ( ) { } ... . } public struct MyStruct { public int i ; public float f ; } public class B { ... } MyClass myClass = new MyClass ( ) ; | How does C # create an instance of a class ? |
C# | Suppose I have the following array ( my sequences are all sorted in ascending order , and contain positive integers ) I want to write a linq query to select the continuous numbers in a series treated as a group . So , in above example I would get { [ 1 , 2 , 3 ] , [ 7 , 8 , 9 ] , [ 15 , 16 , 17 ] } .I could write a for... | var mySequence = new [ ] { 1 , 2 , 3 , 7 , 8 , 9 , 15 , 16 , 17 } ; internal class Sequence { public int Start { get ; set ; } public int End { get ; set ; } } internal static class EnumerableMixins { public static IEnumerable < Sequence > GroupFragments ( this IEnumerable < int > sequence ) { if ( sequence.Any ( ) ) {... | LINQ Query to identify fragments in a series |
C# | I created an Class which is only able to handle primitive ( or ICloneable ) TypesI want to know if it 's possible to say something like : or do I really need to create a constructor for each primitive type like : What I am trying to achieve is to create an object with 3 public properties Value , Original and IsDirty.Th... | public myobject ( primitiv original ) { ... } public myobject ( int original ) { ... } public myobject ( bool original ) { ... } ... | How to tell a constructor it should only use primitive types |
C# | If I have a string like thisHow can I parse it such that the result would be three string `` words '' which have the following content : Edit 2 : note that the quotation marks are to be retainedAt first , I attempted by using string.Split ( ' ' ) , but I noticed that it would make the third string broken to few other s... | create myclass `` 56 , 'for the better or worse ' , 54.781 '' [ 0 ] create [ 1 ] myclass [ 2 ] `` 56 , 'for the better or worse ' , 54.781 '' create myclass false `` 56 , 'for the better or worse ' , 54.781 '' //orcreate myclass `` 56 , 'for the better or worse ' , 54.781 '' false //Examples : // [ 1 ] ( 2 + 1 ) * ( 5 ... | Parse string with whitespace and quotation mark ( with quotation mark retained ) |
C# | I have dimensional list : I would do binary search by the first column ( words ) , something like this : but it works only for a one-dimensional list . How would I extend it to work for two-dimensional lists in my case ? I do n't want to use Dictionary class . | List < List < string > > index_en_bg = new List < List < string > > ( ) ; index_en_bg.Add ( new List < string > ( ) { word1 , translation1 } ) ; index_en_bg.Add ( new List < string > ( ) { word2 , translation2 } ) ; index_en_bg.Add ( new List < string > ( ) { word3 , translation3 } ) ; int row = index_en_bg.BinarySearc... | BinarySearch in two dimensional list |
C# | My Question is simpleVB.dll ( VB5.0 I guess ) includes these methodsin C # ... . ( .NET 4.5 ) The first one works great , but the second one spilt this error . A call to PInvoke function 'ffr_data_transceive_ex ' has unbalanced the stack . This is likely because the managed PInvoke signature does not match the unmanage... | Private Declare Function ffr_device_find Lib `` .\ffr_32.dll '' ( ) As BooleanPrivate Declare Function ffr_data_transceive_ex Lib `` .\ffr_32.dll '' ( ByVal sp_sdata As String , ByVal sp_rdata As String ) As Boolean [ DllImport ( `` FFR_32.dll '' , CallingConvention = CallingConvention.Cdecl ) ] extern public static Bo... | VB5 dll , how can I invoke the function from C # ( .NET 4.5 ) |
C# | Here 's what I am trying to write : The signature of the Bar ( ) method is : So I get a compile error because the T in Foo 's signature does n't have the same constraint . Unfortunately I ca n't write : because Foo is implementing a method defined in an external interface . Question is : Can I somehow transpose the T w... | public void Foo < T > ( T parameter ) { otherObject.Bar < T > ( parameter ) ; } public void Bar < T > ( T parameter ) where T : class public void Foo < T > ( T parameter ) where T : class { otherObject.Bar < T > ( parameter ) ; } | How to cast a generic parameter ? |
C# | I have a windows TCP service , which has many devices connecting to it , and a client can have one or more devices.Requirement : Separate Folder per client with separate log file for each device.so something like this : Now I have not used a 3rd Party library like log4net or NLog , I have a class which handles this.And... | /MyService/25-04-2016/ Client 1/ Device1.txt Device2.txt Device3.txt Client 2/ Device1.txt Device2.txt Device3.txt public class xPTLogger : IDisposable { private static object fileLocker = new object ( ) ; private readonly string _logFileName ; private readonly string _logFilesLocation ; private readonly int _clientId ... | Separate Logfile and directory for each client and date |
C# | In C # , volatile keyword ensures that reads and writes have acquire and release semantics , respectively . However , does it say anything about introduced reads or writes ? For instance : | volatile Thing something ; volatile int aNumber ; void Method ( ) { // Are these lines ... var local = something ; if ( local ! = null ) local.DoThings ( ) ; // ... guaranteed not to be transformed into these by compiler , jitter or processor ? if ( something ! = null ) something.DoThings ( ) ; // < -- Second read ! //... | Does volatile prevent introduced reads or writes ? |
C# | I 'm refreshing my memory on how reference and value types work in .NET . I understand that the entry on the stack for a reference type contains a pointer to a memory location on the heap . What I ca n't seem to find details about is what else the stack entry contains . So , given the following : After the first line o... | Customer customer ; customer = new Customer ( ) ; | What does the stack entry for a reference type contain ? |
C# | Given an Expression < Func < TEntity , bool > > along the lines ofI am trying to extract a list property conditions by type , i.e.So far , I have created an ExpressionVisitor and identified the VisitBinary method as the one I want to plug into in order to obtain my information.I am still at a loss abouthow to determine... | entity = > entity.SubEntity.Any ( subEntity = > ( ( subEntity.SomeProperty == False ) AndAlso subEntity.SubSubEntity.FooProperty.StartsWith ( value ( SomeClass+ < > c__DisplayClass0 ) .ComparisonProperty ) AndAlso subEntity.SubSubEntity.BarProperty == `` Bar '' AndAlso subEntity.SubSubEntity.SubSubSubEntity.Any ( subSu... | Extract all conditions from Expression by Type |
C# | UPDATE : I 've found the answer , which I will post in a couple of days if nobody else does.I am creating a numeric struct , so I am overloading the arithmetical operators . Here is an example for a struct that represents a 4-bit unsigned integer : The overloaded addition operator allows this code : Here , the calculat... | public struct UInt4 { private readonly byte _value ; private const byte MinValue = 0 ; private const byte MaxValue = 15 ; public UInt4 ( int value ) { if ( value < MinValue || value > MaxValue ) throw new ArgumentOutOfRangeException ( `` value '' ) ; _value = ( byte ) value ; } public static UInt4 operator + ( UInt4 a ... | Overloading the + operator so it is sensitive to being called in a checked or unchecked context |
C# | I am very new to programming and I have a question , I am trying to use Regex method to extract hours , minutes and seconds from a string and putting them into an array , but so far I can do it with only one number : How do manage to read from a string 06 : 11 : 33 , and transform these hours , minutes and seconds into... | int initialDay D = 0 ; string startDay = Console.ReadLine ( ) ; //input : `` It started 5 days ago '' var resultString = Regex.Match ( startDay , @ '' \d+ '' ) .Value ; initialDay = Int32.Parse ( resultString ) ; // initialDay here equals 5. int [ ] array = new int [ ] { n1 , n2 , n3 } ; // the n1 would be 6 , n2 would... | Regex extract from string xx : xx : xx format |
C# | I have developed a small-ish C # console application ( TextMatcher.exe ) on my local development machine and now need to deploy it to the live environment . It references another class library which I developed which has generic functions , which I intend to use and improve in future console applications.Ultimately thi... | E : /TextMatcher > TextMatcher.exeNoE : /TextMatcher > | C # application says `` No '' when executed |
C# | I need to split List < IInterface > to get lists of concrete implementations of IInterface.How can I do it in optimal way ? | public interface IPet { } public class Dog : IPet { } public class Cat : IPet { } public class Parrot : IPet { } public void Act ( ) { var lst = new List < IPet > ( ) { new Dog ( ) , new Cat ( ) , new Parrot ( ) } ; // I need to get three lists that hold each implementation // of IPet : List < Dog > , List < Cat > , Li... | C # split List of interface by implementations |
C# | I have a predicate Expression < Func < T1 , bool > > I need to use it as a predicate Expression < Func < T2 , bool > > using the T1 property of T2 I was trying to think about several approches , probably using Expression.Invoke but couln ; t get my head around it.For reference : AndThanks a lot in advance . | class T2 { public T1 T1 ; } Expression < Func < T1 , bool > > ConvertPredicates ( Expression < Func < T2 , bool > > predicate ) { //what to do here ... } | Linq - Creating Expression < T1 > from Expression < T2 > |
C# | I read of a useful trick about how you can avoid using the wrong domain data in your code by creating a data type for each domain type you 're using . By doing this the compiler will prevent you from accidentally mixing your types.For example , defining these : allows me to not mix up meters and seconds because they 'r... | public struct Meter { public int Value ; public Meter ( int value ) { this.Value = value ; } } public struct Second { public int Value ; public Second ( int value ) { this.Value = value ; } } Meter distance = new Meter ( 5 ) ; Meter distance = 5 ; | Is there any way to implicitly construct a type in C # ? |
C# | consider the following code : //This prints 53954 . Why ? ? and //This prints 40000 . how ? ? any help appreciable ... | ushort a = 60000 ; a = ( ushort ) ( a * a / a ) ; Console.WriteLine ( `` A = `` + a ) ; ushort a = 40000 ; a = ( ushort ) ( a * a / a ) ; Console.WriteLine ( `` a = `` + a.ToString ( ) ) ; | confusion with result of Ushort |
C# | I have static method like this : and I use it as following : How write method that return the following results ? s1 : `` ID '' s2 : `` Age '' s3 : `` Name '' * return each property ` s name after = > as string | public static string MyMethod ( Func < Student , object > func ) { return ? ? ? ; } var s1 = MyMethod ( student = > student.ID ) ; // Return `` ID '' ? ? ? var s2 = MyMethod ( student = > student.Age ) ; // Return `` Age '' ? ? ? var s3 = MyMethod ( student = > student.Name ) ; // Return `` Name '' ? ? ? | How Func < DomainObject , object > return Object name as string |
C# | In C # resizing an array ( increasing its size in this case ) initializes the new segment with default values – is this reliable ? I do see the default values ( 0 for byte arrays ) , but is it possible to safely take that as the standard behavior for all base types ? In my application saving every second is a big deal ... | Array.Resize ( ref bytes , bytes.Length + extra ) ; | In C # resizing an array ( increasing its size in this case ) initializes the new segment with default values – is this reliable ? |
C# | I have been looking into speeding up my application as it is performance critical ... i.e . every millisecond I can get out of it is better . To do this I have a method that calls some other methods and each of these other methods is wrapped with a Stopwatch timer and Console.WriteLine calls . I.e . : The problem is wh... | private void SomeMainMethod ( ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; SomeMethod ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Time for SomeMethod = { 0 } ms '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; SomeOtherMethod ( ) ; sw.Stop ( ) ; Console.WriteLi... | Console.WriteLine speeds up my code ? |
C# | In C # , you can do something like this : What is this syntax called ? | SomeClass someClass = new SomeClass ( ) { SomeProperty = someValue } ; | What is the name of this C # syntax ? |
C# | In the below example I have created a class named 'Custom ' that implements IComparable : Implementations of CompareTo ( Object ) are generally `` forgiving '' in that they will cast 'value ' to a more specific type . In this case , a cast to the type 'Custom ' will be performed so a comparison can be made . Imagine I ... | public int CompareTo ( Object value ) { // comparison logic here } public static bool operator== ( Custom lhs , Custom rhs ) { // equivalence test here } Custom c = GetCustomObject ( ) ; Object o = GetOtherObject ( ) ; if ( c == o ) { // will not be true unless c and o are the same object } public static bool operator=... | How to handle operator == overload when the right hand side is of type Object |
C# | I came across this and am curious as to why is it not possible to use the is operator to discern between bool and Nullable < bool > ? Example ; Calling Main ( ) gives ; I 'd expect ; Why do both bool and Nullable < bool > match each other ? What have I tried ; I 've consulted the docs for Nullable , is , switch and pat... | void Main ( ) { bool theBool = false ; Nullable < bool > theNullableBoolThatsFalse = false ; Nullable < bool > theNullableBoolThatsNull = null ; void WhatIsIt ( object value ) { if ( value is bool ) Console.WriteLine ( `` It 's a bool ! `` ) ; if ( value is Nullable < bool > ) Console.WriteLine ( `` It 's a Nullable < ... | Why is it not possible to use the is operator to discern between bool and Nullable < bool > ? |
C# | I have a problem with generic . When I try to use less operators in generic , their call is not happening . But it works with the method Equals.That is a some test class : And class Checker : Small testing : How I can use less operators in class Test from generic ? | public class Test { public int i ; static public Boolean operator == ( Test obj1 , Test obj2 ) { Console.WriteLine ( `` operator == '' ) ; return obj1.i == obj2.i ; } static public Boolean operator ! = ( Test obj1 , Test obj2 ) { Console.WriteLine ( `` operator ! = '' ) ; return obj1.i ! = obj2.i ; } public override bo... | C # generics class operators not working |
C# | I have people and places data as : Person entity hasIList < DateRangePlaces > each havingIList < Place > of possible places Schedule day pattern as ie . 10 days available 4 unavailableWithin a particular DateRangePlaces date range one has to obey to Schedule pattern whether person can go to a particular place or not.Pl... | for each Place { for each Day between minimum and maximum date in IList < DateRangeTiming > { get a set of People applicable for Place and on Day } } Person.IList < DateRangePlaces > .IList < Place > Person.IList < DateRangePlaces > .IDictionary < int , Place > Place.IList < Permission > Person.IList < DateRangePermiss... | Advanced : How to optimize my complex O ( n² ) algorithm |
C# | I frequently find myself wanting to do something along these lines : Of course the compiler will now complain that this code is not valid , since ClientSize is a property , and not a variable.We can fix this by setting the ClientSize in its entirety : Or , in general : But this is all looks unnecessary and obfuscated .... | Form form = new Form ( ) ; form.ClientSize.Width = 500 ; form.ClientSize = new Size ( 500 , ClientSize.Height ) ; Size s = form.ClientSize ; s.Width = 500 ; form.ClientSize = s ; //only necessary if s is a value-type . ( Right ? ) | Why can we not set properties of properties ? |
C# | I think I 'm going mad , someone please reassure me.People keep on adding code like the above in to our code base , surely this is wrong and horrid and I am doing the world a favour by deleting it and replacing all ( or both in this case ... ) references to it with the internal code.Is there any real justification for ... | public class MyFile { public static byte [ ] ReadBinaryFile ( string fileName ) { return File.ReadAllBytes ( fileName ) ; } public static void WriteBinaryFile ( string fileName , byte [ ] fileContents ) { File.WriteAllBytes ( fileName , fileContents ) ; } } | Methods which wrap a single method |
C# | I 'm an absolute beginner when it comes to C # . Trying to learn via examples . So I 've found myself a nice little calculator tutorial . Everything goes fine up to last moment , the code is working , but it does n't take multi-digit input like 33 . There 's a bool statement there for turning arithmetic operations on/o... | public partial class MainWindow : Window { double value = 0 ; string operation = `` '' ; bool operation_pressed = false ; public MainWindow ( ) { InitializeComponent ( ) ; } private void button_Click ( object sender , RoutedEventArgs e ) { if ( ( tb.Text == `` 0 '' ) || ( operation_pressed == true ) ) tb.Clear ( ) ; op... | C # bool statement throws strange exception for seemingly unconnected double.parse ( string ) |
C# | I would like to have four buttons like this : On an iPhone or a small mobile I would like to have these fill 90 % of the screen width . But on a bigger screen I would like the buttons to only fill 50 % of the screen width . Can anyone suggest to me how I can do this ? | < Grid x : Name= '' buttonGrid '' Grid.Row= '' 3 '' Grid.Column= '' 0 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' Center '' Padding= '' 20 , 0 '' > < Button x : Name= '' zeroButton '' Text= '' 0 '' HeightRequest= '' 60 '' BackgroundColor= '' # 2D7BF7 '' HorizontalOptions= '' FillAndExpand '' VerticalO... | How can I achieve four spaced buttons on an iPhone that fill the screen and on bigger than an iPhone that fill half the screen ? |
C# | How to match the sentence that start with `` أقول `` by this code ? This is an arbic word . `` أقول `` What is the regular expression exactly ? | Regex.Matches ( Content , `` أقول `` ) ; | How to match the sentence that start with `` أقول `` by this code ? |
C# | I have a DataTemplate Column with 2 DatePickers that are bound to 2 properties . When the data in these control is changed only last control gets updatedIn this case if I update both Start and Due Only Due gets updated . Also the binding works fine because if I put a breakPoint on Start in my Model class it gets hit bu... | < sdk : DataGridTemplateColumn Width= '' 300 '' CanUserReorder= '' False '' > < sdk : DataGridTemplateColumn.CellTemplate > < DataTemplate > < Grid MouseRightButtonDown= '' ActionsGrid_MouseRightButtonDown '' Width= '' 300 '' Height= '' 40 '' MouseLeftButtonDown= '' ActionsGrid_MouseLeftButtonDown '' > < StackPanel Ori... | Only last control in Data Template column getting updated |
C# | I have 2 scenarios.This fails : error CS0102 : The type ' F < X > ' already contains a definition for ' X ' This works : The only logical explanation is that in the second snippet the type parameter X is out of scope , which is not true ... Why should a type parameter affect my definitions in a type ? IMO , for consist... | class F < X > { public X X { get ; set ; } } class F < X > { class G { public X X { get ; set ; } } } class F { class X { } public X X { get ; set ; } } class X { } class F { public X X { get ; set ; } } | 'Lexical ' scoping of type parameters in C # |
C# | I want to see the real time use of Volatile keyword in c # . but am unable to project the best example . the below sample code works without Volatile keyword how can it possible ? In the above code i am getting a value as 5. how it works without using volatile keyword ? | class Program { private static int a = 0 , b = 0 ; static void Main ( string [ ] args ) { Thread t1 = new Thread ( Method1 ) ; Thread t2 = new Thread ( Method2 ) ; t1.Start ( ) ; t2.Start ( ) ; Console.ReadLine ( ) ; } static void Method1 ( ) { a = 5 ; b = 1 ; } static void Method2 ( ) { if ( b == 1 ) Console.WriteLine... | What is the volatile keyword purpose in c # ? |
C# | BackgroundI have a website that displays data unique to a client . The site required views to be created ever time a new client is added . Each client is unique and has a different identifying information unique to them . For example an ID number and a prefix.Everytime a new client is added a new set of views is manual... | string connectionString = fmDbSelect ( ) ; using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { using ( SqlCommand command = new SqlCommand ( ) ) { command.Connection = connection ; connection.Open ( ) ; var scripts = Regex.Split ( sql , @ '' ^\w+GO $ '' , RegexOptions.Multiline ) ; foreach ( v... | How to Dynamically Create Views ? |
C# | I 'm using structure map with the AspNet Core 1.0 RTM . It appears they have removed using the FromServices attribute on properties . This breaks the code below because I am now unable to inject the ClaimsPrincipal . I 'm not sure how to get the DI system to pickup this property . Do I need to create a custom InputForm... | public class Startup { public IServiceProvider ConfigureServices ( IServiceCollection services ) { var container = new Container ( ) ; container.Configure ( i = > { i.For < IHttpContextAccessor > ( ) .Use ( new HttpContextAccessor ( ) ) ; i.For < ClaimsPrincipal > ( ) .Use ( x = > x.GetInstance < IHttpContextAccessor >... | Asp.Net Core RC1 - > RTM DI changes - Removed FromServices |
C# | I 'm currently working on an application that combines many streams of data through equations . What I 'd like to be able to do is something like : Where result updates whenever any of the streams update . At the moment the only way I can express this in Rx is as : Which is n't nearly as clear.My current idea is as fol... | var result = ( stream1 + stream2 ) / stream3 + stream4 * 2 ; var result = stream1.CombineLatest ( stream2 , ( x , y ) = > x+y ) .CombineLatest ( stream3 , ( x , y ) = > x / y ) .CombineLatest ( stream4 , ( x , y ) = > x + y*2 ) ; Public class ArithmeticStream : IObservable < double > { public static ArithmeticStream op... | Stream Arithmetic with Reactive Extensions |
C# | I have a List of type string in a .NET 3.5 project . The list has thousands of strings in it , but for the sake of brevity we 're going to say that it just has 5 strings in it.Assume that the list is sorted ( as you can tell above ) . What I need is a LINQ query that will remove all strings that are not duplicates . So... | List < string > lstStr = new List < string > ( ) { `` Apple '' , `` Banana '' , `` Coconut '' , `` Coconut '' , `` Orange '' } ; | Query a list for only duplicates |
C# | I have subscribed various event in OnNavigatedTo like I have n't unsubscribed this event . Does it cause any memory issue when this page is not needed ? ? | protected override void OnNavigatedTo ( NavigationEventArgs e ) { Loaded += Screen_Loaded ; } | Do I need to unsubscribe from an event in a c # metro application ? |
C# | I am trying to pull multiple elements out of an XML documents and their children but I can not find a useful example anywhere ... MSDN is very vague . This is c # in .NetI am creating this XML dynamically already and transferring it to a string . I have been trying to use XmlNode with a NodeList to go through each file... | < searchdoc > < results > < result no = `` 1 '' > < url > a.com < /url > < lastmodified > 1/1/1 < /lastmodified > < description > desc1 < /description > < title > title1 < /title > < /result > < result no = `` 2 '' > < url > b.com < /url > < lastmodified > 2/2/2/ < /lastmodified > < description > desc2 < /description >... | Can I get a specific example of XML in c # |
C# | EDIT : The bounty 's expired , but if the community would like to award it to someone , then I choose Raful Chizkiyahu.I have a memory leak in one of my C # Winforms programs , and I 'd like to graph its memory usage over time to get a better understanding of what might be causing the leak . Problem is , none of the us... | private void timer1_Tick ( object sender , EventArgs e ) { //Refresh ( ) ; label1.Text = `` Environment.WorkingSet : `` + Environment.WorkingSet ; label2.Text = `` GC.GetTotalMemory ( false ) : `` + GC.GetTotalMemory ( false ) ; label3.Text = `` GC.GetTotalMemory ( true ) : `` + GC.GetTotalMemory ( true ) ; Process pro... | Contradictory reporting of total Process memory usage in C # Winforms app |
C# | I 'd like to know how should I do to test simple C # expressions 1 ) in Visual Studio and 2 ) not in debug , in design mode Say , I want to verify what will return this codeOr I obtained in the immediate window the following message : | ? DateTime.ParseExact ( `` 2016 '' , `` yyyy '' ) int i ; int.TryParse ( `` x55 '' , out i ) ; ? i ? DateTime.ParseExact ( `` 2016 '' , `` yyyy '' ) The expression can not be evaluated while in design mode . | Test simple c # code expressions in Visual Studio |
C# | If I execute the code below , OutOfMemoryException occurs at either the lineor the linewhen the inner for statement executed about 1000 times.However , I do n't know why OutOfMemoryException occurs . I think I have written enough using to dispose Bitmap objects . Where does the memory leak occurs ? EDIT : OK. Maybe it ... | using ( Bitmap bitmap1 = new Bitmap ( FrameToFilePath ( interval.Start - 1 ) ) ) using ( Bitmap bitmap2 = new Bitmap ( FrameToFilePath ( interval.End + 1 ) ) ) class Program { static void Main ( string [ ] args ) { // Some code to initialize List < Interval > intervals Parallel.ForEach ( intervals , interval = > { usin... | C # Bitmap - Can not find how to remove OutOfMemoryException |
C# | I am writing some unit test for an ApiController . I continue to get multiple System.MissingMethodException exceptions for methods in the System.Web.Http namespace . Message : System.MissingMethodException : Method not found : 'System.Net.Http.HttpRequestMessage System.Web.Http.ApiController.get_Request ( ) ' . Message... | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < packages > < package id= '' AutoMapper '' version= '' 8.1.0 '' targetFramework= '' net461 '' / > < package id= '' EntityFramework '' version= '' 6.1.3 '' targetFramework= '' net461 '' / > < package id= '' log4net '' version= '' 2.0.8 '' targetFramework= '' net461 '... | System.Web.Http methods missing in Nunit test project |
C# | I encountered a weird problem : given such string { `` text '' : '' s '' , '' cursorPosition '' :189 , '' dataSource '' : '' json_northwind '' , which is not a correct json , it still gets succesfully parsed.this is the class : Here is test that surprisingly succeeds : does the library have some loosened parsing rules ... | public class CompletionDataRequest { public CompletionDataRequest ( string text , int cursorPosition , string dataSource , string project ) { Text = text ; CursorPosition = cursorPosition ; DataSource = dataSource ; Project = project ; } public string Text { get ; } public int CursorPosition { get ; } public string Dat... | Newtonsoft.Json parses incorrect json |
C# | In a project I 'm currently working on , I am starting an external process . However , the external process is the EXE of a complex program which loads current-user information from a user folder . The desktop shortcut for the program resolves the matter by setting the `` Target : '' parameter to X : \exepath\prgm.exe ... | Process p = new Process ( ) ; p.StartInfo = new ProcessStartInfo ( `` X : \exepath\prgm.exe '' ) ; p.StartInfo.WorkingDirectory = `` X : \exepath\users\username '' ; p.Start ( ) ; while ( ! p.HasExited ) { } | More than one important path for .NET Process |
C# | I have the following line of code : Which results in an IOException being thrown . Additional information : The process can not access the file ' C : \Users\Username\AppData\Local\Temp\dgl5fb1i.err ' because it is being used by another process.However , this is a part of a large program that consumes more than 8GB of R... | CSharpCodeProvider c = new CSharpCodeProvider ( ) ; CompilerParameters cp = new CompilerParameters ( ) ; cp.ReferencedAssemblies.Add ( `` system.dll '' ) ; cp.CompilerOptions = `` /t : library '' ; cp.GenerateInMemory = true ; CompilerResults cr = c.CompileAssemblyFromSource ( cp , sb.ToString ( ) ) ; | IOException when dynamically compiling code |
C# | What happens exactly during string initialization ? Is it going to make a call to any of these constructors ? | string s = `` Hello World ! `` ; public String ( char* value ) ; public String ( char [ ] value ) ; | What happens during string initialization ? |
C# | C # has a conditional operator and IF statements and I suspected that the conditional operator would be just syntactic sugar . So at compile time it would have a the same as an IF operation . However they do not ( see below ) , they do have different IL . Trying to wrap my head around it and the assumption I have is th... | var result = `` '' ; if ( Environment.Is64BitOperatingSystem ) { result = `` Yes '' ; } else { result = `` No '' ; } Console.WriteLine ( result ) ; Console.WriteLine ( `` Is the OS x64 ? { 0 } '' , Environment.Is64BitOperatingSystem ? `` Yes '' : `` No '' ) ; L_0001 : ldstr `` '' L_0006 : stloc.0 L_0007 : call bool [ m... | Why such a difference in IL between IF and the conditional operator ? |
C# | The two methods above seems to behave equally , both when passing null reference or boxed T value . However , the generated MSIL code is a bit different : vsAs you may see , the o is T ? expression actually performs type check for Nullable < T > type , despite the fact that nullable types are specially handled by CLR s... | class C < T > where T : struct { bool M1 ( object o ) = > o is T ; bool M2 ( object o ) = > o is T ? ; } .method private hidebysig instance bool M1 ( object o ) cil managed { .maxstack 8 IL_0000 : ldarg.1 IL_0001 : isinst ! T IL_0006 : ldnull IL_0007 : cgt.un IL_0009 : ret } .method private hidebysig instance bool M2 (... | Is there a difference between ` x is int ? ` and ` x is int ` in C # ? |
C# | I found a piece of code of the following form : In other parts of the code , I want to get the same lightweight CustomerContact object , only not from the Invoice , but from the Customer itself . So the obvious thing to do would be to have : and then change the Expression taking Invoice as input to refer to this method... | public static Expression < Func < Invoice , CustomerContact > > GetCustomerContact ( ) { return i = > new CustomerContact { FirstName = i.Customer.FirstName , LastName = i.Customer.LastName , Email = i.Customer.Email , TelMobile = i.Customer.TelMobile , } ; } public static Expression < Func < Customer , CustomerContact... | Syntax to refer a method returning an Expression to another method ? |
C# | Is it possible to use the return value of a function instead of a specific value as optional parameter in a function ? For example instead of : I want something like | public void ExampleMethod ( int a , int b , int c=10 ) { } private int ChangeC ( int a , int b ) { return a+b ; } public void ExampleMethod ( int a , int b , int c=ChangeC ( a , b ) ) { } | Use a function to define an optional parameter |
C# | I have this code that creates a request and reads the data but it is always emptyWhen i try to access the link from browser i get this json : what am I missing ? | static string uri = `` http : //yiimp.ccminer.org/api/wallet ? address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd '' ; static void Main ( string [ ] args ) { HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip ; HttpW... | Reading data from url returns empty value |
C# | Hi i am new in c # and i want to ask how to write this code more pretyAll it do just copy all properties except id . Can i write it shortly ? Thanx and sorry for my bad english | public void Update ( Product pr ) { Product prod = GeProductById ( pr.ProductID ) ; prod.Name = pr.Name ; prod.Count = pr.Count ; prod.InputPrice = pr.InputPrice ; prod.InputDate = pr.InputDate ; prod.OutPrice = pr.OutPrice ; prod.InputPriceByCurrency = pr.InputPriceByCurrency ; prod.InputPriceCurrency = pr.InputPriceC... | How to write it pretty ? |
C# | I wrote this piece of code : and the reflector gives me : Obviously , this is not what the original code says . The line ( this._queue = new Queue < int > ( 10 ) ) ; will alway return a new Queue < int > ( 10 ) instead of _queue when it is not null.Is this a bug in the .NET Reflector or am I missing something ? The pro... | private Queue < int > EnsureQueue ( ) { return _queue ? ? ( _queue = new Queue < int > ( 10 ) ) ; } private Queue < int > EnsureQueue ( ) { if ( this._queue == null ) { } return ( this._queue = new Queue < int > ( 10 ) ) ; } | Is the .NET Reflector unable to reflect over the null-coalescing operator correctly ? |
C# | In `` Getting Started with Asynchronous Programming in .NET '' by Filip Ekberg , in the `` Asynchronous Programming Deep Dive/Working with Attached and Detached Tasks '' chapter , he says that by using the service value inside the async anonymous method , it introduces a closure and unnecessary allocation : Next , he s... | using System ; public class C { public void M ( ) { var i = 1 ; Func < int > f = ( ) = > i + 1 ; f ( ) ; } } public class C { [ CompilerGenerated ] private sealed class < > c__DisplayClass0_0 { public int i ; internal int < M > b__0 ( ) { return i + 1 ; } } public void M ( ) { < > c__DisplayClass0_0 < > c__DisplayClass... | What is the allocation being saved here ? |
C# | By calling Push ( ) and Pop ( ) an instance of Stack < T > in a single line I get a different behavior than performing the imho same code in two lines.The following code snippet reproduces the behavior : The Element class is really basic : With this code I get the following result ( .NET 3.5 , Win 7 , fully patched ) :... | static void Main ( string [ ] args ) { Stack < Element > stack = new Stack < Element > ( ) ; Element e1 = new Element { Value = `` one '' } ; Element e2 = new Element { Value = `` two '' } ; stack.Push ( e1 ) ; stack.Push ( e2 ) ; Expected ( stack ) ; // element on satck has value `` two '' //Unexpected ( stack ) ; // ... | Unexpected operation order in Stack < T > related one liner |
C# | I have the following C # code trying to benchmark under release mode : I am on a 64-bit machine and VS 2015 installed . When I run the code under 32-bit , it runs each iteration around 0.6 seconds , printed to the console . When I run it under 64-bit then the duration for each iteration simply jumps to 4 seconds ! I tr... | using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication54 { class Program { static void Main ( string [ ] args ) { int counter = 0 ; var sw = new Stopwatch ( ) ; unchecked { int sum = 0 ; while ( tru... | Slow execution under 64 bits . Possible RyuJIT bug ? |
C# | Following this very interesting issue which was originated from this question -I want to take 1 steps back please ( removed the dynamic environment ) : Looking at this code : ( a variant of this one ) The result is : This is understood : The x = 1 is from the method itself ( using Console.Writeline ) in bool operator f... | void Main ( ) { int a ; int b = 100 ; Console.WriteLine ( X.M ( 1 , out a ) ) ; } public class X { public int H=0 ; public static X M ( int x , out int y ) { Console.WriteLine ( `` x = `` +x ) ; y = x ; return new X ( x ) ; } public X ( ) { } public X ( int h ) { H=h ; } public static bool operator false ( X x ) { Cons... | & & operator overloading and assignments in C # - Clarification ? |
C# | First my question , and then some details : Q : Do I need to stub the value of a property when making sure its value is used in a subsequent assignment ? Details : I 'm using Rhino Mocks 3.5 's AAA syntax in MSpec classes . I 've trimmed the code below to keep it ( hopefully ) easy to grok . *Not Stubbing _fooResultMoc... | [ Subject ( `` Foo '' ) ] public class when_foo { Establish context = ( ) = > { _fooDependencyMock.Stub ( x = > x.GetResult ( ) ) .Return ( _fooResultMock ) ; _foo = new Foo ( _fooDependencyMock ) ; } ; Because action = ( ) = > { _foo.Whatever ( ) ; } ; It should_set_the_name_field = ( ) = > { _fooTargetMock.AssertWasC... | Rhino Mocks : stubbing value used in assertion ? |
C# | Let 's say I have the following input : and expect the following output : The logic is a square which needs to be turned by 90 degrees to the right - but without linebreak.The width should be dynamic and always Is there a easy approach to solve this ? | string input = `` 123456789 '' ; string output = `` 741852963 '' ; // squares//INPUT OUTPUT// 123 ══╗ 741// 456 V 852// 789 963 int width = ( int ) Math.Sqrt ( input.Length ) ; | Sort a string by Linq |
C# | On occasion we get some robots that like to post bad information to our website ( they are attempting some kind of reflection attack ) but luck for us the attempts are stopped via the default input validation that one gets with MVC.This is nice and all , but now we want to see what the robots are actually sending and w... | public void OnException ( ExceptionContext filterContext ) { HttpRequestValidationException hex = filterContext.Exception as HttpRequestValidationException ; if ( hex == null ) { return ; } // Get the data . This will explode throwing the same exception ( ` HttpRequestValidationException ) . Is n't there a way that we ... | MVC see input that caused exception |
C# | Below is a console app that demonstrates the issue : Output is `` False True True '' .I 've used SOS.dll to try to find what holds the delegates from being GCed and here is what I get for the Action : Can someone explain what is going on ? | class Program { static void Main ( ) { InitRefs ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ( _refObj.IsAlive ) ; Console.WriteLine ( _refAction.IsAlive ) ; Console.WriteLine ( _refEvent.IsAlive ) ; Console.ReadKey ( ) ; } private static void InitRefs ( ) { _refObj = new WeakReference ( n... | Delegates do not get garbage collected |
C# | I am trying to change the Background of some errorneous data containing cells in a WPF DataGrid by using this code : However , upon doing this , the above change of background-color change is occuring to cells in the same column , periodically after every 14 ( aprox . ) rows as I scroll down the DataGrid . It is only i... | DataGridRow gridRow = dgInventory.ItemContainerGenerator.ContainerFromIndex ( 0 ) as DataGridRow ; DataGridCell cell = dgInventory.Columns [ 1 ] .GetCellContent ( gridRow ) .Parent as DataGridCell ; cell.Background = Brushes.Gray ; gridRow.IsSelected = true ; gridRow.Focus ( ) ; | Changing a cell in a row of a DataGrid ( WPF ) is changing cells in rows below |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.