lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I am trying to add unit-tests for my code where I am using Task from TPL to update values into a database . For unit-test , I am using NUnit and Moq . Here are some code snippets from my project.This is working . But when I add ContinueWith with the service method call like this ... this test code is not working.Test i... | *//service*public interface IServiceFacade { Task SynchronizeDataset ( string datasetName ) ; } *//The method call I want to test*_ServiceFacade.SynchronizeDataset ( DATASET_NAME ) ; *//In my test , I want to verify if this method is called*mock_IServicesFacade.Setup ( sf = > sf.SynchronizeDataset ( It.IsAny < string >... | Unit test is failing when ContinueWith is used with System.Threading.Tasks.Task |
C# | This has been driving me nuts all day , as I 've made no changes yet I swear this was working the way I had intended yesterday.I have a WCF 4 REST service defined with the following contract : I also have the following types defined : Yesterday I swear I was able to submit POST data of this form : Today that same batch... | [ ServiceContract ] public interface IPhoneFeaturesManagementHost { [ OperationContract ] [ WebInvoke ( Method = `` POST '' , UriTemplate = `` /accounts/ { accountNumber } /phoneNumbers/ { phoneNumber } /features/ { featureType } '' , RequestFormat = WebMessageFormat.Xml , ResponseFormat = WebMessageFormat.Xml , BodySt... | REST with Polymorphic DataContracts - Deserialization Fails |
C# | Below is an implementation of ForEachAsync written by Stephen ToubWhat factors should be considered when specifying a partitionCount ( dop in this case ) ? Does the hardware make a difference ( # of cores , available RAM , etc ) ? Does the type of data/operation influence the count ? My first guess would be to set dop ... | public static Task ForEachAsync < T > ( this IEnumerable < T > source , int dop , Func < T , Task > body ) { return Task.WhenAll ( from partition in Partitioner.Create ( source ) .GetPartitions ( dop ) select Task.Run ( async delegate { using ( partition ) while ( partition.MoveNext ( ) ) await body ( partition.Current... | Factors for determining partitionCount for C # Partitioner.GetPartitions ( ) |
C# | I am trying to do a comparison of a MySqlDateTime object to another MySqlDateTime object , each from two different tables . I am trying to do all of this inside a LINQ query , ex : This gives me a compiler error : Operator '== ' can not be applied to operands of type 'MySql.Data.Types.MySqlDateTime ' and 'MySql.Data.Ty... | var prodRowFindQuery = from x in production.AsEnumerable ( ) where x.Field < MySqlDateTime > ( `` date '' ) == row.Field < MySqlDateTime > ( `` date '' ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ; var prodRowFindQuery = from x in production.AsEnumerable ( ) where... | MySqlDateTime in LINQ Query |
C# | I 'm not sure if there is a pattern that should be used here but here is the situation : I have a number of concrete classes that implement an interface : I have another class that checks input to determine if ShouldPerformAction should be execute . The rub is that new checks are added fairly frequently . The interface... | public interface IPerformAction { bool ShouldPerformAction ( ) ; void PerformAction ( ) ; } public interface IShouldPerformActionChecker { bool CheckA ( string a ) ; bool CheckB ( string b ) ; bool CheckC ( int c ) ; // etc ... } public class ConcreteClass : IPerformAction { public IShouldPerformActionCheck ShouldPerfo... | Design pattern question for maintainability |
C# | The code below works fine , just wondering if there 's a more elegant way of achieving the same thing ? The dates below should be valid , anything other than that should not:1/12/20171/12/2017 11:101/12/2017 11:10:3015/5/201715/5/2017 11:1015/5/2017 11:10:301/5/20171/5/2017 11:101/5/2017 11:10:3025/12/201725/12/2017 11... | var validDateTimeFormats = new [ ] { `` d/MM/yyyy '' , `` d/MM/yyyy HH : mm '' , `` d/MM/yyyy HH : mm : ss '' , `` dd/M/yyyy '' , `` dd/M/yyyy HH : mm '' , `` dd/M/yyyy HH : mm : ss '' , `` d/M/yyyy '' , `` d/M/yyyy HH : mm '' , `` d/M/yyyy HH : mm : ss '' , `` dd/MM/yyyy '' , `` dd/MM/yyyy HH : mm '' , `` dd/MM/yyyy H... | C # DateTime.TryParseExact with optional parameters |
C# | Consider the following code : By running this code , we are able to change the contents of a string without an exception occuring . We did not have to declare any unsafe code to do so . This code is clearly very dodgy ! My question is simply this : Do you think that an exception should be thrown by the code above ? [ E... | using System ; using System.Runtime.InteropServices ; namespace Demo { class Program { static void Main ( string [ ] args ) { const string test = `` ABCDEF '' ; // Strings are immutable , right ? char [ ] chars = new StringToChar { str=test } .chr ; chars [ 0 ] = ' X ' ; // On an x32 release or debug build or on an x64... | Should changing the contents of a string like this cause an exception ? |
C# | I 'm generating some code via Cecil . The code generates without error , but when I try to load the assembly I get : An unhandled exception of type 'System.InvalidProgramException ' occurred in DataSerializersTest.exe Additional information : Common Language Runtime detected an invalid program.Here is the generated IL ... | .method public static class Data.FooData Read ( class [ mscorlib ] System.IO.BinaryReader input ) cil managed { // Method begins at RVA 0x3a58 // Code size 60 ( 0x3c ) .maxstack 3 .locals ( [ 0 ] class Data.FooData , [ 1 ] valuetype [ System.Runtime ] System.Nullable ` 1 < int32 > ) IL_0000 : newobj instance void Data.... | What is wrong with this CIL ? |
C# | I have an application where the parent object has a method to perform validations and every child overrides the method to perform extra validations . Something like : I added a new `` IsDisabled '' property that when true the method will not perform any validations.I also want that for every child , if the `` IsDisable... | class Parent { virtual void DoValidations ( Delegate addErrorMessage ) { //do some validations } } class Child : Parent { override void DoValidations ( Delegate addErrorMessage ) { base.DoValidations ( addErrorMessage ) ; //the parent method is always called //do some extra validations } } class Parent { boolean IsDisa... | Conditionally block method override |
C# | My boss just told me that he learned about fast VB6 algorithms from a book and that the shortest way to write things is not necessarily the fastest ( e.g . builtin methods are sometimes way slower than selfwritten ones because they do all kinds of checking or unicode conversions which might not be necessary in your cas... | if ( a ( ) ) b ( ) ; a ( ) & & b ( ) ; | Speed of different constructs in programming languages ( Java/C # /C++/Python/… ) |
C# | In assigning event handlers to something like a context MenuItem , for instance , there are two acceptable syntaxes : ... and ... I also note that the same appears to apply to this : ... and ... Is there any particular advantage for the second ( explicit ) over the first ? Or is this more of a stylistic question ? | MenuItem item = new MenuItem ( `` Open Image '' , btnOpenImage_Click ) ; MenuItem item = new MenuItem ( `` Open Image '' , new EventHandler ( btnOpenImage_Click ) ) ; listView.ItemClick += listView_ItemClick ; listView.ItemClick += new ItemClickEventHandler ( listView_ItemClick ) ; | Is there a benefit to explicit use of `` new EventHandler '' declaration ? |
C# | In VB6 there are local static variables that keep their values after the exit of procedure . It 's like using public vars but on local block . For example : After 10 calls , x will be 10 . I tried to search the same thing in .NET ( and even Java ) but there was none . Why ? Does it break the OOP model in some way , and... | sub count ( ) static x as integerx = x + 1end sub | VB6 's private static in C # ? |
C# | I have the following code ( simplified for posting purposes ) .The idea is that when DoRequest call is made , SomeDataObject will get some data and raise either the Ready or Error events ( details not important ! ) . If data is available , then the ItemCount indicates how many items are available.I am new to Rx and can... | public class SomeDataObject { public delegate void ReadyEventHandler ; public delegate void ErrorEventHandler ; public event ReadyEventHandler Ready ; public event ErrorEventHandler Error ; ... } pubic class ConsumerClass { private SomeDataObject dataObject ; private Task < List < string > > GetStrings ( ) { List < str... | Convert Event based code to Rx |
C# | TL ; DR : Why is wrapping the System.Numerics.Vectors type expensive , and is there anything I can do about it ? Consider the following piece of code : This will JIT into ( x64 ) : and x86 : Now , if I wrap this in a struct , e.g.and change GetIt , e.g.the JITted result is still exactly the same as when using the nativ... | [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static long GetIt ( long a , long b ) { var x = AddThem ( a , b ) ; return x ; } private static long AddThem ( long a , long b ) { return a + b ; } 00007FFDA3F94500 lea rax , [ rcx+rdx ] 00007FFDA3F94504 ret 00EB2E20 push ebp 00EB2E21 mov ebp , esp 00EB2E23 mov ea... | Expensive to wrap System.Numerics.VectorX - why ? |
C# | I have this bank ATM mock-up app which implements some Domain-Driven Design architecture and Unit of Work pattern . This app have 3 basic functions : Check balanceDepositWithdrawThese are the project layers : ATM.Model ( Domain model entity layer ) ATM.Persistence ( Persistence Layer ) ATM.ApplicationService ( Applicat... | namespace ATM.Model { public class BankAccount { public int Id { get ; set ; } public string AccountName { get ; set ; } public decimal Balance { get ; set ; } public decimal CheckBalance ( ) { return Balance ; } public void Deposit ( int amount ) { // Domain logic Balance += amount ; } public void Withdraw ( int amoun... | Why the database data is not being updated but object did and without error ? |
C# | In C++ , you can write code like this : But , you ca n't do something like this in C # : Is there any reason why ? I know it could be accomplished through reflection ( generic Add with objects and then run type checking over it all ) , but that 's inefficient and does n't scale well . So , again , why ? | template < class T > T Add ( T lhs , T rhs ) { return lhs + rhs ; } public static T Add < T > ( T x , T y ) where T : operator+ { return x + y ; } | Why cant you require operator overloading in generics |
C# | My web app currently allows users to upload media one-at-a-time using the following : The media then gets posted to a WebApi controller : Which then does something along the lines of : This is working great for individual uploads , but how do I go about modifying this to support batched uploads of multiple files throug... | var fd = new FormData ( document.forms [ 0 ] ) ; fd.append ( `` media '' , blob ) ; // blob is the image/video $ .ajax ( { type : `` POST '' , url : '/api/media ' , data : fd } ) [ HttpPost , Route ( `` api/media '' ) ] public async Task < IHttpActionResult > UploadFile ( ) { if ( ! Request.Content.IsMimeMultipartConte... | Batched Media Upload to Azure Blob Storage through WebApi |
C# | The C # specification ( ECMA-334 and ISO/IEC 23270 ) has a paragraph about the atomicity of reads and writes : 12.5 Atomicity of variable references Reads and writes of the following data types shall be atomic : bool , char , byte , sbyte , short , ushort , uint , int , float , and reference types . In addition , reads... | // sizeof ( MyStruct ) == 9 [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] struct MyStruct { public byte pad ; // Offset : 0 public int value1 ; // Offset : 1 public int value2 ; // Offset : 5 } MyStruct myStruct = new MyStruct ( ) ; myStruct.value1 = 20 ; | Are reads and writes to unaligned fields in .NET definitely atomic ? |
C# | Ok this looks like a major fundamental bug in .NET : Consider the following simple program , which purposely tries to connect to a non-existent database : Run this program and set breakpoints on the catch blocks . The DBConnection object will attempt to connect for 15 seconds ( on both threads ) , then it will throw an... | class Program { static void Main ( string [ ] args ) { Thread threadOne = new Thread ( GetConnectionOne ) ; Thread threadTwo = new Thread ( GetConnectionTwo ) ; threadOne.Start ( ) ; threadTwo.Start ( ) ; } static void GetConnectionOne ( ) { try { using ( SqlConnection conn = new SqlConnection ( `` Data Source=.\\wfea ... | Connection Pool returns Same Exception Instance to Two Threads Using the Same Bad Connection String ? |
C# | I have declared the following Enum : and i want to retrieve the enum object from is value : Call Examples : I would also like to use linq or lambda , only if they can give better or equals performance . | public enum AfpRecordId { BRG = 0xD3A8C6 , ERG = 0xD3A9C6 } private AfpRecordId GetAfpRecordId ( byte [ ] data ) { ... } byte [ ] tempData = new byte { 0xD3 , 0xA8 , 0xC6 } ; AfpRecordId tempId = GetAfpRecordId ( tempData ) ; //tempId should be equals to AfpRecordId.BRG | Get Enum name based on the Enum value |
C# | Small background : I 'm the only programmer for this company . I 'm working with pre-existing frameworks.That said , the company has a dll ( Database.dll ) which contains `` all the database interactions I need '' . As in , it has a Query ( ) , Update ( ) , Insert ( ) , etc . Now , the project I 'm writing sets a refer... | var query = string.Format ( `` SELECT timestamp FROM table1 WHERE date = \ '' { 0 } \ '' AND measured_dist = bit_loc AND rop > 0 '' , Date ) ) | When to worry about SQL injection protection |
C# | I have some logic for Task and Task < T > . Is there any way to avoid duplicating code ? My current code is following : | public async Task < SocialNetworkUserInfo > GetMe ( ) { return await WrapException ( ( ) = > new SocialNetworkUserInfo ( ) ) ; } public async Task AuthenticateAsync ( ) { await WrapException ( ( ) = > _facebook.Authenticate ( ) ) ; } public async Task < T > WrapException < T > ( Func < Task < T > > task ) { try { retur... | Avoiding duplicate methods for Task and Task < T > |
C# | I have : A structA class containing the structWhen I now instantiate my class , I assume that the struct lives on the heap.If I now do something likewill it be passed as value ? If not , is there any reason not to make the struct into a class instead ? | struct Data { int a ; int b ; } class Packet { Data DataStruct ; } SomeClass.Process ( new Packet ( ) .DataStruct ) ; SomeClass.Process ( new Packet ( ) .DataStruct.a ) ; | Are structs within classes passed as value ? |
C# | I 'm going to preface this question with the statement : I know the following is bad design , but refactoring is not currently an option , ideally it should be done using interceptors.I am working on upgrading castle from 1.6 ( I think ) to 3.3 which unfortunately involves some syntax changes , I 've got everything com... | RepositoryRegistration < IAccountRepository , AccountRepositoryFeedEntryDecorator > ( ) .DependsOn ( Dependency.OnComponent ( `` decoratedRepository '' , typeof ( AccountRepositoryAuthorizationDecorator ) ) ) , RepositoryRegistration < AccountRepositoryAuthorizationDecorator > ( ) .DependsOn ( Dependency.OnComponent ( ... | What is the difference between a Component and a Service dependency ? |
C# | I 'm implementing sortable columns on my Kendo grid and the user-expected behaviour is to allow multiple columns to be sorted at the same time.Naturally , I 'm starting off by writing a unit test to be able to verify that the sorting is ( by default ) first by Ref ascending , then Name ascending.Test suppliers in quest... | _context.Suppliers.Add ( new Supplier { Ref = `` abc '' , Name = `` steve '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` abc '' , Name = `` bob '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` cde '' , Name = `` ian '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` fgh '' , Name = `` dan '' ... | How to verify that multiple sorts have been applied to a collection ? |
C# | I have a method that queries a rest API where I do a mapping from JSON to an object . Since the query string and object type I pass to this method always have to match I wanted to include the query string as a static string . | public class Root { public static string Query ; } public class RootObject : Root , IRootObject { public D d { get ; set ; } public static new string Query = `` AccountSet '' ; } public interface IRootObject { D d { get ; } } public class RestClass { public void Connect < T > ( ) where T : Root , IRootObject { T.Query ... | How can i associate a static string with an object type C # |
C# | This question inspired me to ask the following question . Does the DllImport attribute always loads the specific DLL even when you 're not calling/using the method.For example when you have the following code : Now when the application is started the AllocConsole will never be fired but will the dll be loaded anyway ? | static class Program { [ DllImport ( `` kernel32.dll '' ) ] static extern bool AllocConsole ( ) ; static void Main ( ) { if ( true ) { //do some things , for example starting the service . } else { AllocConsole ( ) ; } } } | Is the DllImport attribute always loading the unmanaged DLL |
C# | I want to create a card trick game using C # . I 've designed Picture Boxes on the form to be the cards ( backside ) . I also created a Click method for each of the pictures that creates a random number between 0 , 51 and use the number to set an image from an ImageList . My problem is that sometimes I get the same num... | Random random = new Random ( ) ; int i = random.Next ( 0 , 51 ) ; pictureBox1.Image = imageList1.Images [ i ] ; | An issue in designing a Card Trick Game using C # |
C# | I often find that attributes can be too large.Sometimes it feels like the attributes take up more of the screen than the code.It can make it hard to spot the method names.Also , they are not reusable , so you can end up repeating your values a lot.To counter this I considered creating my own attribute class , which inh... | [ SoapDocumentMethod ( `` http : //services.acme.co.uk/account/Web/GetCustomerDetails/GetCustomerDetails '' , RequestNamespace = `` http : //services.acme.co.uk/account/Web '' , ResponseNamespace = `` http : //services.acme.co.uk/account/Web '' , Use = SoapBindingUse.Literal , ParameterStyle = SoapParameterStyle.Wrappe... | Is there an alternative to large messy attributes ? |
C# | I 'm using MongoDb 2.6.10 and using C # Driver 1.9.2 . The server has a replicaset of two servers.My documents are of the format . itemId is unique.Then I have code to remove a favorite of the formAfter each time , I check that result.DocumentsAffected is equal to 1 . Once in a while , the value comes back as 0 . When ... | { `` itemID '' : 2314 , `` Favorites '' : [ 1 , 24 , 26 , 34 ] } var query = Query.EQ ( `` itemID '' , itemId ) ; var result = collection.Update ( query , Update.Pull ( `` Favorites '' , favoriteIdToRemove ) ) ; | Mongo update response says no document updated , but the document is there |
C# | This was originally a much more lengthy question , but now I have constructed a smaller usable example code , so the original text is no longer relevant.I have two projects , one containing a single struct with no members , named TestType . This project is referenced by the main project , but the assembly is not includ... | using System ; [ Serializable ] public struct TestType { } using System ; using System.Reflection ; using System.Reflection.Emit ; internal sealed class Program { [ STAThread ] private static void Main ( string [ ] args ) { Assembly assemblyCache = null ; AppDomain.CurrentDomain.AssemblyResolve += delegate ( object sen... | Cross-AppDomain call corrupts the runtime |
C# | I 'm currently dealing with reflection in c # . After : And i found this : [ System.Numerics.Matrix4x4 ] , [ System.Numerics.Matrix4x4+CanonicalBasis ] , [ System.Numerics.Matrix4x4+VectorBasis ] ( There are reflected types from `` System.Numerics.Vectors.dll '' ) I know that Matrix4x4 is structture , however I ca n't ... | Assembly.LoadFile ( @ '' C : \Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll '' ) .GetTypes ( ) Assembly.LoadFile ( @ '' C : \Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll '' ) .GetType ( `` System.Numerics.Matrix4x4+VectorBasis '' ) .FullName '... | What does `` + '' mean in reflected FullName and '* ' after Member c # |
C# | I 'm trying to create a type similar to Rust 's Result or Haskell 's Either and I 've got this far : Given that both types parameters are restricted to be notnull , why is it complaining ( anywhere where there 's a type parameter with the nullable ? sign after it ) that : A nullable type parameter must be known to be a... | public struct Result < TResult , TError > where TResult : notnull where TError : notnull { private readonly OneOf < TResult , TError > Value ; public Result ( TResult result ) = > Value = result ; public Result ( TError error ) = > Value = error ; public static implicit operator Result < TResult , TError > ( TResult re... | C # 's ca n't make ` notnull ` type nullable |
C# | I know Since the release of msbuild 15 ( vs 2017 ) that NuGet is now fully integrated into MSBuild.I have a nuspec file with defining variables of package properties like : The nuspec file is located in the same folder of the project.When using nuget tool to create the package , it works fine . When using msbuild v15 ,... | < metadata > < id > $ id $ < /id > < version > $ version $ < /version > < authors > $ authors $ < /authors > ... < /metadata > nuget pack msbuild -version msbuild /t : pack /p : configuration=release /p : NuspecFile=mylib.nuspec | Msbuild v15 ca n't resolve the variables of metadata of nuspec file |
C# | I 'm trying to create Unit Test . I have class User : My first test is UsersCount_Test test which tests UsersCount property : If I add new test method in my test class ( I 'm using separate classes for testing each entity ) , I need to create new instance of User . That 's why I did this : Now each test classes inherit... | public class User { public int UsersCount { get { using ( MainContext context = new MainContext ( ) ) { return context.Users.Count ( ) ; } } } public Guid Id { get ; set ; } = Guid.NewGuid ( ) ; public string UserName { get ; set ; } public string Password { get ; set ; } public Contact UserContact { get ; set ; } } [ ... | How to get test initialize in memory and use in each test |
C# | I need to make a simple check if a dds file is of valid format . I just need to do a general check of the dds file , so I do not need to check if it is a dxt1 , dxt5 , dx10 etc . For example if I have a png image and I rename the extensions to .dds the dds format will ofcourse be wrong and I would then need to tell the... | var png = new byte [ ] { 0x89 , 0x50 , 0x4e , 0x47 , 0x0D , 0x0A , 0x1A , 0x0A } using ( FileStream fs = new FileStream ( fileToCheck , FileMode.Open , FileAccess.Read ) ) { if ( fs.Length > buffer.Length ) { fs.Read ( buffer , 0 , buffer.Length ) ; fs.Position = ( int ) fs.Length - endBuffer.Length ; fs.Read ( bufferE... | How can I make sure that a DirectDraw surface has a correct file format ? |
C# | I have the following query : Which is used to query a SQLite in-memory DB as : However when I try to read the values as Int32 I get InvalidCastException.The reason why I am using dapper like so is that as a side project I am building some features on top of dapper to map the values to a POCO ( I am aware of the similar... | SELECT [ Person ] . [ Id ] AS [ Person_Id ] , [ Person ] . [ Name ] AS [ Person_Name ] , [ Address ] . [ Id ] AS [ Address_Id ] , [ Address ] . [ Number ] AS [ Address_Number ] , [ Address ] . [ Street ] AS [ Address_Street ] , FROM [ Person ] LEFT JOIN [ Address ] ON [ Person ] . [ addressId ] = [ Address ] . [ Id ] v... | Why is dapper returning every number column as Int64 ? |
C# | For instance : I have array Who know fast method to find index of tag 's array ? I need something as following : a sequence can be in more than one times in src.Solution : How to find index of sublist in list ? | var src = new byte [ ] { 1 , 2 , 3 , 4 , 5 } ; var tag = new byte [ ] { 3 , 4 } ; int FindIndexOfSeq ( byte [ ] src , byte [ ] sequence ) ; | How to determine that one array is a part of another one ? |
C# | I am new to c # . I would like to know if a string such as a user name contains a specific word . I want to get those specific words from an array.Here 's a example. ` ( Update ) Thank you all but me learning c # only for about a month could not cover lambda or regex yet . I will have a look at these codes while later ... | Console.Write ( `` Name : `` ) ; _name = Console.ReadLine ( ) ; name = Program.ProperNameMethod ( _name ) ; Console.WriteLine ( ) ; string [ ] badWordArray = { `` aBadword1 '' , `` aBadWord2 '' , `` aBadWord3 '' } ; if ( ! string.IsNullOrEmpty ( name ) // Would like to check for the badwordarray aswell ) | Check if a string contains a specific string using array |
C# | I am using Telerik Gridview for displaying list of records and i have more than 10 pages on which i am using this gridview with this following common events code copy pasted ( with some minor changes ) on all this pages : This is my one page which inherits from following page : So is this possible that i can place all ... | protected void Page_Load ( object sender , EventArgs e ) { DisplayRecords ( ) } public void DisplayRecords ( ) { //Grid view names are different on different pages . GridView1.DataSource=Fetching records from database . GridView1.DataBind ( ) ; } protected void GridView1_SortCommand ( object sender , GridSortCommandEve... | How to delegate telerik grid view common methods to be call from parent page from every child page ? |
C# | I 'm trying to remove duplicate entries from a list which contains a generic object.And the code to remove the dupes : The problem is Equals and GetHashCode is never called . Anyone have any idea why ? | public class MessageInfo { public DateTime Date { get ; set ; } public string To { get ; set ; } public string Message { get ; set ; } } public class SMSDupeRemover : IEqualityComparer < MessageInfo > { public bool Equals ( MessageInfo x , MessageInfo y ) { throw new NotImplementedException ( ) ; } public int GetHashCo... | Simple IEqualityComparer < T > question |
C# | I am writing an Android ( Xamarin ) application which is able to zoom and pan an image . A user can also click on a position on the image . I need those coordinates on the image for later use.The following code is zooming and panning the image : So far so good , now I have some MotionEvent in use , which is a LongPress... | protected override void OnDraw ( Canvas canvas ) { base.OnDraw ( canvas ) ; _maxX = canvas.Width ; _maxY = canvas.Height ; canvas.Translate ( _posX , _posY ) ; if ( _scaleDetector.IsInProgress ) canvas.Scale ( _scaleFactor , _scaleFactor , _scaleDetector.FocusX , _scaleDetector.FocusY ) ; else canvas.Scale ( _scaleFact... | Android : Get correct coordinates with scaled and translated canvas |
C# | You 'll appreciate the following two syntactic sugars : andClearly the first example in each case is more readable . Is there a way to define this kind of thing myself , either in the C # language , or in the IDE ? The reason I ask is that there are many similar usages ( of the long kind ) that would benefit from this ... | lock ( obj ) { //Code } same as : Monitor.Enter ( obj ) try { //Code } finally { Monitor.Exit ( obj ) } using ( var adapt = new adapter ( ) ) { //Code2 } same as : var adapt= new adapter ( ) try { //Code2 } finally { adapt.Dispose ( ) } myclass { ReaderWriterLockSlim rwl = new ReaderWriterLockSlim ( ) ; void MyConcurre... | Does this feature exist ? Defining my own curly brackets in C # |
C# | I know that 'new ' keyword will call the constructor and initialize the object in managed heap.My question is how the CLR doing the below.How the above line is executed by CLR ? How the memeory is allocated for the object by CLR ? How CLR determine the size of the object ? How CLR will come know it , if there is no spa... | MyObject obj = new MyObject ( ) ; | What is happening when I give MyObject obj = new MyObject ( ) |
C# | I 've always been explicit with my code when using instance members , prefixing them with this . and with static members , prefixing them with the type name.Roslyn seems not to like this , and politely suggests that you can omit this . and Type . from your code where appropriate ... ... so where I would do this ... ( n... | public void DoSomethingCool ( ) { this.CallAwesomeMethod ( ) ; CoolCucumber.DoSomethingLessAewsome ( ) ; } public void DoSomethingCool ( ) { CallAwesomeMethod ( ) ; DoSomethingLessAwesome ( ) ; } public int GetTotal ( ) { // This does n't work return Sum ( o = > o.Value ) ; // This does return this.Sum ( o = > o.Value ... | Roslyn code analyzers - when should I use `` this . `` ? |
C# | If you put the following code in your compiler the result is a bit bizar : Result : decimal x = 275.99999999999999999999999double y = 276.0Can someone explain this to me ? I do n't understand how this can be correct . | decimal x = ( 276/304 ) *304 ; double y = ( 276/304 ) *304 ; Console.WriteLine ( `` decimal x = `` + x ) ; Console.WriteLine ( `` double y = `` + y ) ; | decimal rounding is off for ( 276/304 ) *304 |
C# | I have been looking for an answer to this for 2 days now . I 'm not even sure exactly what is wrong , but I think I may have pinpointed the possible culprit . My program is a database tracker/manager that will keep track of the equipment at my company . The user can query for , create , and edit equipment . Right now ,... | public class Equipment { public int EquipmentId { get ; set ; } //required public string Company { get ; set ; } //required public bool Verified { get ; set ; } //required ( ... other non-required attributes ... ) //The following two attributes are where my problems are I believe [ ForeignKey ( `` PAU '' ) ] public int... | Database Validation Errors . Allow nullable value in one table but not in related ( normalized ) table |
C# | Ugly : Better ( maybe monad ) : Even better ? Any reason this could n't be written ? | string city = null ; if ( myOrder ! = null & & myOrder.Customer ! = null ) city = myOrder.Customer.City ; var city = myOrder .With ( x = > x.Customer ) .With ( x = > x.City ) var city = Maybe ( ( ) = > myOrder.Customer.City ) ; | Maybe monad using expression trees ? |
C# | Is there a way how to programmatically enable/disable usage of property name specified by [ JsonProperty ] ? When I serialize : I would like to be able to see an output `` in debug '' : And `` in release '' : | public class Dto { [ JsonProperty ( `` l '' ) ] public string LooooooooooooongName { get ; set ; } } { `` LooooooooooooongName '' : '' Data '' } { `` l '' : '' Data '' } | Enable/disable usage of specified [ JsonProperty ] name |
C# | I have this method in c # , and I wish to refactor it . There are just too many bools and lines . What would be the best refactoring . Making a new class seems a bit overkill , and cutting simply in two seems hard . Any insight or pointer would be appreciated.method to refactor | private DialogResult CheckForSireRestrictionInSubGroup ( bool deletingGroup , string currentId ) { DialogResult result = DialogResult.No ; if ( ! searchAllSireList ) { DataAccessDialog dlg = BeginWaitMessage ( ) ; bool isClose = false ; try { ArrayList deletedSire = new ArrayList ( ) ; ISireGroupBE sireGroupBE = sireCo... | Refactoring a method with too many bool in it |
C# | I am writing a very simple utility class with the aim to measure the time executed for any method passed in ( of any type ) .In my case Membership.ValidateUser ( model.UserName , model.Password ) return bool so I get an exception.I would like if would be possible write a utililty class of this type an a sample of code ... | Tracing.Log ( Membership.ValidateUser ( model.UserName , model.Password ) , `` Membership.ValidateUser '' ) ; public static class Tracing { public static void Log ( Action action , string message ) { // Default details for the Log string sSource = `` TRACE '' ; string sLog = `` Application '' ; // Create the Log if ( !... | How to count time elapsed for a method with an utility class |
C# | So , I 'm trying to have a parent/child class relationship like this : But , this is a compile error . So , my second thought was to declare the SetParent method with a where . But the problem is that I do n't know what type declare myParent as ( I know the type , I just so n't know how to declare it . ) | class ParentClass < C , T > where C : ChildClass < T > { public void AddChild ( C child ) { child.SetParent ( this ) ; //Argument 1 : can not convert from 'ParentClass < C , T > ' to 'ParentClass < ChildClass < T > , T > ' } } class ChildClass < T > { ParentClass < ChildClass < T > , T > myParent ; public void SetParen... | Parent/Child Generics Relationship |
C# | I 've been optimising/benchmarking some code recently and came across this method : This is called from a performance critical loop elsewhere , so I naturally assumed all those typeof ( ... ) calls were adding unnecessary overhead ( a micro-optimisation , I know ) and could be moved to private fields within the class .... | public void SomeMethod ( Type messageType ) { if ( messageType == typeof ( BroadcastMessage ) ) { // ... } else if ( messageType == typeof ( DirectMessage ) ) { // ... } else if ( messageType == typeof ( ClientListRequest ) ) { // ... } } [ DisassemblyDiagnoser ( printAsm : true , printSource : true ) ] [ RyuJitX64Job ... | Why is typeA == typeB slower than typeA == typeof ( TypeB ) ? |
C# | The following ruby code runs in ~15s . It barely uses any CPU/Memory ( about 25 % of one CPU ) : And the following TPL C # puts all my 4 cores to 100 % usage and is orders of magnitude slower than the ruby version : How come ruby runs faster than C # ? I 've been told that Ruby is slow . Is that not true when it comes ... | def collatz ( num ) num.even ? ? num/2 : 3*num + 1endstart_time = Time.nowmax_chain_count = 0max_starter_num = 0 ( 1..1000000 ) .each do |i| count = 0 current = i current = collatz ( current ) and count += 1 until ( current == 1 ) max_chain_count = count and max_starter_num = i if ( count > max_chain_count ) endputs ``... | How come this algorithm in Ruby runs faster than in Parallel 'd C # ? |
C# | I try to get a X509Certificate2 from a BountyCastle X509Certificate and a PKCS12 . I use the following code : I generate the rawData , like the following : The problem is , that I get the following exception : After some days of researching , I figured out , that the problem is based on the Mono implementation of ASN1 ... | certificate = new X509Certificate2 ( rawData , password , storageFlags ) ; using ( MemoryStream pfxData = new MemoryStream ( ) ) { X509CertificateEntry [ ] chain = new X509CertificateEntry [ 1 ] ; chain [ 0 ] = new X509CertificateEntry ( x509 ) ; pkcsStore.SetKeyEntry ( applicationName , new AsymmetricKeyEntry ( subjec... | BouncyCastle undefined length ASN1 |
C# | I 'm trying to close my Main Window from a child window in my WPF application . The problem is , once I try to 'close ' the main window , my whole application closes.Here is my coding from my main window ( pgLogin ) : And my child window ( pgDashboard ) : Is there a way to close the main window without hiding it and st... | Window nextWindow = null ; nextWindow = new pgDashboard ( ) ; nextWindow.Owner = this ; this.Hide ( ) ; nextWindow.Show ( ) ; public static T IsWindowOpen < T > ( string name = null ) where T : Window { var windows = Application.Current.Windows.OfType < T > ( ) ; return string.IsNullOrEmpty ( name ) ? windows.FirstOrDe... | How to stop MainWindow from closing whole application |
C# | I am using the Memory Management while returning the data like below.Query - Is there any issue in placing the 'Using ' Statement while returning the data ? I am Still getting the complete schema as well as the data in the receiving function ? | private DataSet ReturnDs ( ) { using ( DataSet ds = new DataSet ( ) ) { return ds ; } } | Using Statement while returning data |
C# | This is something I 've never understood . It almost seems like a hack to create a dummy object that gets locked , like the examplefrom https : //msdn.microsoft.com/en-us/library/c5kehkcz.aspx.Why could n't the language designers make it so that would be equivalent ? | class Account { decimal balance ; private Object thisLock = new Object ( ) ; public void Withdraw ( decimal amount ) { lock ( thisLock ) { if ( amount > balance ) { throw new Exception ( `` Insufficient funds '' ) ; } balance -= amount ; } } } class Account { decimal balance ; public void Withdraw ( decimal amount ) { ... | Why do we need to lock and object in C # ? |
C# | I 'm returning Streams from a remote service ( .NET Remoting ) . But Streams are also disposables which as we all know are ment to be disposed.I could call Dispose on the client side once I finished consuming those . However , I would like to know what exactly happens under the cover when I return a Stream from a remot... | public static class ServiceFactory < T > { public static T CreateProxy ( ) { Type interfaceType = typeof ( T ) ; string uri = ApplicationServer.ServerURL + interfaceType.FullName ; return ( T ) Activator.GetObject ( interfaceType , uri ) ; } } | What happens under the cover when you return a Stream from a remote object via .NET Remoting |
C# | Suppose I had two classes : We have here the descriptions of two geometric shapes along with an operation in both.And here 's my attempt in F # : Suppose I made an observation about these two classes ( they both have Height ! ) and I wanted to extract an operation that made sense for anything that had a height property... | public class Triangle { public float Base { get ; set ; } public float Height { get ; set ; } public float CalcArea ( ) { return Base * Height / 2.0 ; } } public class Cylinder { public float Radius { get ; set ; } public float Height { get ; set ; } public float CalcVolume ( ) { return Radius * Radius * Math.PI * Heig... | C # to F # : Functional thinking vs. polymorphism |
C# | I use Noda Time , and have the following code : This results in an UnparsableValueException with the message : The local date/time is ambiguous in the target time zoneThe problem , as I understand it , is that this specific time can occur twice because of daylight saving . At 02:00 , the clock is turned back one hour t... | var pattern = ZonedDateTimePattern.CreateWithInvariantCulture ( `` yyyy-MM-dd HH : mm : ss z '' , DateTimeZoneProviders.Tzdb ) ; var parsed = pattern.Parse ( `` 2017-11-05 01:00:00 America/Los_Angeles '' ) ; Console.WriteLine ( parsed.Value ) ; | Parsing ambiguous datetime with Noda Time |
C# | Consider , I have the following 3 classes / interfaces : And I want to be able to cast a MyClass < Derived > into a MyClass < IMyInterface > or visa-versa : But I get compiler errors if I try : I 'm sure there is a very good reason why I cant do this , but I ca n't think of one.As for why I want to do this - The scenar... | class MyClass < T > { } interface IMyInterface { } class Derived : IMyInterface { } MyClass < Derived > a = new MyClass < Derived > ( ) ; MyClass < IMyInterface > b = ( MyClass < IMyInterface > ) a ; Can not convert type 'MyClass < Derived > ' to 'MyClass < IMyInterface > ' | Casting generics and the generic type |
C# | The title is possibly worded incorrectly , so please show me the correct terms.I 've got a base class called DAL_Base that accepts a generic type T. The type T comes from our many classes in our Business Objects layer , and each one of them has a corresponding Data Access Layer.DAL_Base accepts parameters that allows m... | public class DAL_Base < T > where T : IDisposable , new ( ) { public DAL_Base < T > ( ) { // < = ERROR HERE // initialize items that will be used in all derived classes } } | Create Instance of a C # Generic Class |
C# | I have a C # public API that is used by many third-party developers that have written custom applications on top of it . In addition , the API is used widely by internal developers.This API was n't written with testability in mind : most class methods are n't virtual and things were n't factored out into interfaces . I... | public class UserRepository { public UserData GetData ( string userName ) { ... } } | How to make an existing public API testable for external programmers using it ? |
C# | Say I have the following : I 'd like to parameterize the tests using the TestCase/TestCaseSource attribute including the call itself . Due to the repetitive nature of the tests , each method needs to be called with slightly different parameters , but I need to be able to tag a different call for each of the different p... | [ Test ] // would like to parameterize the parameters in call AND the call itself public void Test ( ) { var res1 = _sut.Method1 ( 1 ) ; var res2 = _sut.Method2 ( `` test '' ) ; var res3 = _sit.Method3 ( 3 ) ; Assert.That ( res1 , Is.Null ) ; Assert.That ( res2 , Is.Null ) ; Assert.That ( res3 , Is.Null ) ; } | Is there a way to run a list of different action methods on an object in Nunit using TestCase ? |
C# | I know that generics are used to achieve type safety and i frequently read that they are largely used in custom collections . But why actually do we need to have them generic ? For example , Why ca n't I use string [ ] instead of List < string > ? Let 's consider I declare a generic class and it has a generic type para... | T x ; x = x + 1 ; | 'Why ' and 'Where ' Generics is actually used ? |
C# | I can have a nested contracts type for a non-generic interface : But it complains when I try to do the same thing with a generic interface : The warning is : The contract class Foo+FooContracts ` 1 and the type IFoo ` 1 must have the same declaring type if any.It compiles without a warning if I get FooContracts out of ... | [ ContractClass ( typeof ( Foo.FooContracts ) ) ] public interface IFoo { string Bar ( object obj ) ; } [ ContractClass ( typeof ( Foo.FooContracts < > ) ) ] public interface IFoo < T > { string Bar ( T obj ) ; } | Nested contracts for generic interfaces |
C# | Usually , treating a struct S as an interface I will trigger autoboxing of the struct , which can have impacts on performance if done often . However , if I write a generic method taking a type parameter T : I and call it with an S , then will the compiler omit the boxing , since it knows the type S and does not have t... | interface I { void foo ( ) ; } struct S : I { public void foo ( ) { /* do something */ } } class Y { void doFoo ( I i ) { i.foo ( ) ; } void doFooGeneric < T > ( T t ) where T : I { t.foo ( ) ; // < -- - Will an S be boxed here ? ? } public static void Main ( string [ ] args ) { S x ; doFoo ( x ) ; // x is boxed doFooG... | Do C # generics prevent autoboxing of structs in this case ? |
C# | for example : why do we have to add that M ? why not just do : since it already says decimal , doesnt it imply that 25.50 is a decimal ? | const decimal dollars = 25.50M ; const decimal dollars = 25.50 ; | what is the purpose of double implying ? |
C# | I am wondering if there is a way to create a concatenated WHERE clause using an array of int . I need to get the results for the entire array combined . Can I do something like : | public ViewResult Results ( int ? programId , int ? programYear , int ? programTypeId , string toDate , string fromDate , int ? [ ] programTypeIdList , int ? [ ] programIdList ) { surveyResponseRepository.Get ( ) .Any ( x = > x.ProgramId == programIdList ) ; } | Concatenated Where clause with array of strings |
C# | I have this piece of code ( well I have the issue everywhere ) When I debug this , break in the funcion , try to watch some variables . And I keep getting a FileNotFoundExceptionBut the `` missing '' DLL is in the folder , it 's not readonly or any other flags Windows has . | public void PayrollActivityCodeTest ( ) { using ( var pr = new ActivityCodeProcess ( ) ) { pr.Add ( ) ; pr.WorkingEntity.PayrollConfiguration.Provinces = PayrollProvincesType.QC | PayrollProvincesType.ON ; pr.WorkingEntity.ActivityCodeId = `` 01 '' ; //pr.WorkingEntity.Rates.CodeByProvinceCollection.First ( ) .CodeValu... | FileNotFoundException while watching variables in debug mode |
C# | What is the point of writing an interface without members ? INamingContainer is one example in .NET Framework . And it 's described in MSDN as : Identifies a container control that creates a new ID namespace within a Page object 's control hierarchy . This is a marker interface only.Is it used for just this kind of blo... | if ( myControl is INamingContainer ) { // do something } | Why do we use memberless interface ? |
C# | I have n't found a case that fail this condition.So why and when should I use the Marshal method instead of simply getting the GUID property ? | Type classType = typeof ( SomeClass ) ; bool equal = Marshal.GenerateGuidForType ( classType ) == classType.GUID ; | What 's the difference between Marshal.GenerateGuidForType ( Type ) and Type.GUID ? |
C# | How can a C # program detect it is being compiled under a version of C # that does not contain support for the language features used in that program ? The C # compiler will reject the program , and produce some error message , on encountering the features of the language it does not support . This does not address the... | # if CS_VERSION < 3 # error CSharp 3 or later is required # end | How can compilation of C # code be made to require a given language or compiler version ? |
C# | I am using UpdatePanel for asp.net Controls . So , to validate it I am using jquery onEachRequest . It is also working fine.But , main issue is that It stops executing postback of DropDownList . Means , It does not postback to retrive data.My Code : How to solve this issue ? | function onEachRequest ( sender , args ) { if ( $ ( `` # form1 '' ) .valid ( ) ==false ) { args.set_cancel ( true ) ; } } function pageLoad ( ) { $ ( ' # < % = btnPayment.ClientID % > ' ) .click ( function ( ) { $ ( `` # form1 '' ) .validate ( { rules : { < % =txtName.UniqueID % > : { required : true } } , messages : {... | jQuery Validation with Update Panel C # |
C# | LINQ 's AsParallel returns ParallelQuery . I wonder if it 's possible to change this behavior so that I could compare the LINQ statement run with and without parallelism without actually changing the code ? This behavior should be similar to Debug.Assert - when DEBUG preprocessor directive is not set , it 's optimized ... | public static class MyExtensions { # if TURN_OFF_LINQ_PARALLELISM public static IEnumerable < T > AsControllableParallel < T > ( this IEnumerable < T > enumerable ) { return enumerable ; } # else public static ParallelQuery < T > AsControllableParallel < T > ( this IEnumerable < T > enumerable ) { return enumerable.AsP... | LINQ : How to modify the return type of AsParallel depending on a context ? |
C# | This might get closed , but I 'll try anyway.I was showing a VB6 programmer some of my C # code the other day and he noticed the var keyword and was like `` Oh a variant type , that 's not really strong typing when you do that . '' and I had to go on the typical `` var ! = VARIANT '' speech to explain to him that it is... | infer person = new Person ( `` Bob '' ) ; | Better word for inferring variables other than var |
C# | The next 2 lines adds the same amount to the same date , and the results date part is the same , but somehow the there 's difference in the time part ! you 'll get a difference of 15 secs , and with both are at least roundable to days , I do n't know why this happend , but it happens only with AddDays , but not AddMont... | ( new DateTime ( 2000,1,3,18,0,0 ) ) .AddDays ( 4535 ) ; ( new DateTime ( 2000,1,3,18,0,0 ) ) .AddMonths ( 149 ) ; ( new DateTime ( 2000 , 1 , 3 , 18 , 0 , 0 ) ) .AddDays ( 4535 ) .Ticks 634743432153600000 long ( new DateTime ( 2000 , 1 , 3 , 18 , 0 , 0 ) ) .AddMonths ( 149 ) .Ticks 634743432000000000 long | .NET AddDays issue |
C# | In java , we can override or implement abstract methods upon instance creation as follows : Is this possible in C # ? if Yes , what 's the equivalent codeThanks | AbstractClass test =new AbstractClass ( ) { public void AbstractMethod ( string i ) { } public void AbstractMethod2 ( string i ) { } } ; | Override abstract method upon instance creation in c # |
C# | I 've known for a long time that the first statement is incorrect , but it has always bugged me . I 've verified that bar is not null , so why does the compiler complain ? | int foo ; int ? bar ; if ( bar ! = null ) { foo = bar ; // does not compile foo = ( int ) bar ; // compiles foo = bar.Value ; // compiles } | Why is an explicit conversion required after checking for null ? |
C# | The article states the following : http : //msdn.microsoft.com/en-us/library/dd799517.aspxVariance does not apply to delegate combination . That is , given two delegates of types Action < Derived > and Action < Base > ( Action ( Of Derived ) and Action ( Of Base ) in Visual Basic ) , you can not combine the second dele... | Action < B > baction = ( taret ) = > { Console.WriteLine ( taret.GetType ( ) .Name ) ; } ; Action < D > daction = baction ; Action < D > caction = baction + daction ; | Combining delegates and contravariance |
C# | in C # it is possible to apply an attribute to the return of a method : Is this possible in F # ? Background : I would like a method of a library written in F # which will be consumed in a language like C # to return `` dynamic '' from a method . If I look into a similarly defined method compiled from C # it seems like... | [ return : DynamicAttribute ] public object Xyz ( ) { return new ExpandoObject ( ) ; } | Apply attribute to return value - In F # |
C# | I 've searched a bit about type inference , but I ca n't seem to apply any of the solutions to my particular problem.I 'm doing a lot of work with building and passing around functions . This seems to me like it should be able to infer the int type . The only thing I can think of is that the lambda return type is n't c... | Func < T > Test < T > ( Func < Func < T > > func ) { return func ( ) ; } Func < int > x = Test < int > ( ( ) = > { int i = 0 ; return ( ) = > i ; } ) ; Func < int > x = Test ( ( ) = > { int i = 0 ; return ( ) = > i ; } ) ; | Type inference on nested generic functions |
C# | I 'm reading a lossy bit stream and I need a way to recover as much usable data as possible . There can be 1 's in place of 0 's and 0 's in palce of 1 's , but accuracy is probably over 80 % .A bonus would be if the algorithm could compensate for missing/too many bits as well.The source I 'm reading from is analogue w... | Best case data : in : 0000010101000010110100101101100111000000100100101101100111000000100100001100000010000101110101001101100111000101110000001001111011001100110000001001100111011110110101011100111011000100110000001000010111out : 001010100001011010010110110011100000010010010110110011100000010010000110000001000010111010... | Redundancy algorithm for reading noisy bitstream |
C# | I find that using the following : is easier to write and understand than : Are there compelling reasons not to use the first construct ? | TreeViewItem i = sender as TreeViewItem ; if ( i ! = null ) { ... } if ( sender.GetType ( ) == typeof ( TreeViewItem ) ) { TreeViewItem i = ( TreeViewItem ) sender ; ... } | Are there compelling reasons AGAINST using the C # keyword `` as '' ? |
C# | My task is to get directory icons using tasks and display them in a DataGridView ( I 'm performing search through folders ) . For this , I use the SHGetImageList WinAPI function . I have a helper class as the following : On a form I have two DataGridViews and two buttons . On a click of the first button , I load icons ... | using System ; using System.Collections.Generic ; using System.Drawing ; using System.IO ; using System.Linq ; using System.Runtime.InteropServices ; using System.Text ; using System.Threading.Tasks ; namespace WindowsFormsApplication6 { public class Helper { private const uint ILD_TRANSPARENT = 0x00000001 ; private co... | Getting directory icons using tasks |
C# | Let 's say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.Assuming myDisposable do n't dispose the AnotherDisposable inside it 's dispose method.Does this only dispose correctly myDisposable ? or it dispose the AnotherDisposable too ? | using ( MyDisposable myDisposable= new MyDisposable ( new AnotherDisposable ( ) ) ) { //whatever } | Does the using statement dispose only the first variable it create ? |
C# | I 've switched to C # 8 on one of my projects . And I 've been moving all of my switch statements to expressions . However I found out that my project started working differently and I 've found out that it was because of the switch expression . Lets get this code for exampleI 've wrote the result as a comment , but tl... | class Program { public enum DataType { Single , Double , UInt16 , UInt32 , UInt64 , Int16 , Int32 , Int64 , Byte } static void Main ( string [ ] args ) { dynamic value1 = 5 ; dynamic value2 = 6 ; var casted = CastToType ( value1 , DataType.Int16 ) ; var casted1 = CastToTypeExpression ( value2 , DataType.Int16 ) ; var t... | C # Switch expressions returning different result |
C# | I ’ ve got a weird intermittent issue with MVC4 / IIS / Forms Authentication . I ’ ve got a pair of sites that pass control to each other using SSO . Most of the time the handover occurs correctly and the user is redirected to the next site as intended . However , in some cases , the user is asked to log in again , eve... | < location path= '' account/sso '' > < system.web > < authorization > < allow users= '' * '' / > < /authorization > < /system.web > < /location > [ Authorize ] public class AccountController : BaseControllerTestable { public AccountController ( ) : base ( ) { } [ AllowAnonymous ] public ActionResult SSO ( string AuthTo... | MVC4 / IIS / Forms Authentication SSO issue |
C# | I have a chunk of code where sometimes I need to create a new generic type , but with an unknown number of generic parameters . For example : The problem is that if I have more than one Type in my array , then the program will crash . In the short term I have come up with something like this as a stop-gap.This does wor... | public object MakeGenericAction ( Type [ ] types ) { return typeof ( Action < > ) .MakeGenericType ( paramTypes ) ; } public object MakeGenericAction ( Type [ ] types ) { if ( types.Length == 1 ) { return typeof ( Action < > ) .MakeGenericType ( paramTypes ) ; } else if ( types.Length ==2 ) { return typeof ( Action < ,... | Making Generics with many types |
C# | I quite often write code that copies member variables to a local stack variable in the belief that it will improve performance by removing the pointer dereference that has to take place whenever accessing member variables.Is this valid ? For exampleMy thinking is that DoSomethingPossiblyFaster is actually faster than D... | public class Manager { private readonly Constraint [ ] mConstraints ; public void DoSomethingPossiblyFaster ( ) { var constraints = mConstraints ; for ( var i = 0 ; i < constraints.Length ; i++ ) { var constraint = constraints [ i ] ; // Do something with it } } public void DoSomethingPossiblySlower ( ) { for ( var i =... | In C # , does copying a member variable to a local stack variable improve performance ? |
C# | When I scroll vertical scrollbar , DataGrid automatically expands column width if content in new visible rows is bigger and exceeds previous column width . It 's OK.But if all bigger rows are scrolled over and new visible ones have small content width , DataGrid does not decrease column width . Is there a way to archie... | public partial class MainWindow { public MainWindow ( ) { InitializeComponent ( ) ; var persons = new List < Person > ( ) ; for ( var i = 0 ; i < 20 ; i++ ) persons.Add ( new Person ( ) { Name = `` Coooooooooooooool '' , Surname = `` Super '' } ) ; for ( var i = 0 ; i < 20 ; i++ ) persons.Add ( new Person ( ) { Name = ... | WPF DataGrid : reduce column width to fit its content while scrolling |
C# | which one is better from following optionsIs one using statement is enough ? Option 1 : Option 2 : | using ( SqlConnection con = new SqlConnection ( constring ) ) { using ( SqlCommand cmd = new SqlCommand ( ) ) { ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . } } using ( SqlConnection con = new SqlConnection ( constring ) ) { SqlCommand cmd = new SqlCommand ( ) ; ... | C # using keyword , Proper use of it |
C# | I am making a WPF user control and I want similar behavior as DataGrid control in sense of binding . My question is : How does DataGrid know how to bind to any collection of type IEnumerable ? For example : You can pass a DataView as ItemsSource , and you can also pass any object collection . How DataGrid decides wheth... | < DataGridTextColumn Binding= '' { Binding **Path=SomePropertyOrColumn** } '' / > | How does DataGrid bind to properties of any collection ? |
C# | I have implemented a custom state `` blocked '' that moves into the enqueued state after certain external requirements have been fulfilled . Sometimes these external requirements are never fulfilled which causes the job to be stuck in the blocked state . What I 'd like to have is for jobs in this state to automatically... | internal sealed class BlockedState : IState { internal const string STATE_NAME = `` Blocked '' ; public Dictionary < string , string > SerializeData ( ) { return new Dictionary < string , string > ( ) ; } public string Name = > STATE_NAME ; public string Reason = > `` Waiting for external resource '' ; public bool IsFi... | Hangfire Custom State Expiration |
C# | If I override Equals and GetHashCode , how do I decide which fields to compare ? And what will happen if I have two objects with two fields each , but Equals only checks one field ? In other words , let 's say I have this class : I consider two objects Equal if they have the same MyId . So if the Id is equal but the de... | class EqualsTestClass { public string MyDescription { get ; set ; } public int MyId { get ; set ; } public override bool Equals ( object obj ) { EqualsTestClass eq = obj as EqualsTestClass ; if ( eq == null ) { return false ; } else { return MyId.Equals ( eq.MyId ) ; } } public override int GetHashCode ( ) { int hashco... | Overriding Equals ( ) but not checking all fields - what will happen ? |
C# | I have the following code example taken from the code of a Form : The second method ( SomeOtherMethod ) has resharper complaining at me . It says of onPaint that `` Value assigned is not used in any execution path '' .To my mind it was used because I added a method to the list of methods called when a paint was done.Bu... | protected void SomeMethod ( ) { SomeOtherMethod ( this.OnPaint ) ; } private void SomeOtherMethod ( Action < PaintEventArgs > onPaint ) { onPaint += MyPaint ; } protected void MyPaint ( PaintEventArgs e ) { // paint some stuff } | Does adding to a method group count as using a variable ? |
C# | Is there any way for Visual Studio to create my interface 'public ' ? For example , right click on folder - > create new item - > code - > interface.Whenever the file is created there are no access modifiers . Is there any way to default it to make it public ? I 'm always forgetting to manually change them to public ( ... | interface IMyInterface { } public interface IMyInterface { } | Set interface to public by default in C # |
C# | I 'm trying to convert an enum from C++ code over to C # code , and I 'm having trouble wrapping my head around it . The C++ code is : What I do n't understand is what MASK is doing , and how I can either emulate the functionality in C # , or understand what it 's doing and set the enum DISP manually without it.I 'm no... | enum FOO { FOO_1 = 0 , FOO_2 , // etc } # define MASK ( x ) ( ( 1 < < 16 ) | ( x ) ) enum DISP { DISP_1 = MASK ( FOO_1 ) , DISP_2 = MASK ( FOO_2 ) , // etc } | Reproducing some bit shift code from C++ to C # |
C# | I 'm using EF code first for developing my 3 layer WinForm Application , I used disconnected POCOs as my model entities . All my entities inherited from BaseEntity class . I used disconnected POCOs , so I handle entity 's State on client side , and in ApplyChanges ( ) method , I attach my entity graph ( e.g An Order wi... | public class BaseEntity { int _dataBaseId = -1 ; public virtual int DataBaseId // DataBaseId override in each entity to return it 's key { get { return _dataBaseId ; } } public States State { get ; set ; } public enum States { Unchanged , Added , Modified , Deleted } } public static EntityState ConvertState ( BaseEntit... | Finding entities with same key in an object graph for preventing `` An object with the same key already exists in the ObjectStateManager '' Error |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.