lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I know that the general guideline for implementing the dispose pattern warns against implementing a virtual Dispose ( ) . However , most often we 're only working with managed resources inside a class and so the full dispose pattern seems like an overkill - i.e . we do n't need a finalizer . In such cases , is it OK to... | abstract class Base : IDisposable { private bool disposed = false ; public SecureString Password { get ; set ; } // SecureString implements IDisposable . public virtual void Dispose ( ) { if ( disposed ) return ; if ( Password ! = null ) Password.Dispose ( ) ; disposed = true ; } } class Sub : Base { private bool dispo... | Is it OK to have a virtual Dispose ( ) method as long as all classes in the hierarchy only use managed resources ? |
C# | The situation I have is likeExcept I actually want j to go through the range 0-radius.length , but skip over i : I 'm wondering if there 's a way to do this that is compact , elegant , efficient , readable , and maybe even correct.How I planned to do it was | // radius is an int [ ] for ( int i = 0 ; i < radius.length ; ++i ) { for ( int j = 0 ; j < radius.length ; ++j ) { // do some stuff } } { 0,1 , ... , i-1 , i+1 , ... , radius.length } for ( int i = 0 ; i < radius.length ; ++i ) { for ( int j = 0 ; j < radius.length ; ) { // do some stuff j += j ! = i ? 1 : 2 ; } } | Does C # have a nice way of iterating through every integer in a range , minus 1 of them ? |
C# | I am trying one more time to reach out to asp.net experts and hoping to get an answer . I am really stuck here and asking for help . Hopefully , my question will not get down voted , and I could get an answer purely from technical point of view instead of people simply being judgmental on my approach . Earlier I posted... | protected void Page_Load ( object sender , EventArgs e ) { string [ ] filePaths = Directory.GetFiles ( Server.MapPath ( `` ~/ '' ) , `` * . * '' , SearchOption.AllDirectories ) ; foreach ( string filepath in filePaths ) { if ( filepath.EndsWith ( `` .aspx '' ) ) { Response.Write ( filepath + `` < br/ > '' ) ; string [ ... | Identify Label and Button Control in each page of the web project |
C# | This code does not compile : The compile fails stating : Inconsistent accessibility : parameter type Foo is less accessible than method SomeBaseClass.ProcessFoo | internal class Foo { } public abstract class SomeBaseClass { protected internal void ProcessFoo ( Foo value ) { // doing something ... } } | Protected Internal method not allowing Internal Class as parameter |
C# | I have two very similar methods : The top one , will not compile , saying it returns IEnumerable rather than IQueryable.Why is this ? Also , I am aware I can add `` AsQueryable ( ) '' on the end and it will work . What difference does that make though ? Any performance hits ? I understand that IQueryable has deferred e... | public IQueryable < User > Find ( Func < User , bool > exp ) { return db.Users.Where ( exp ) ; } public IQueryable < User > All ( ) { return db.Users.Where ( x = > ! x.deleted ) ; } | Why is my LINQ statement returning IEnumerable ? |
C# | Browsing the .NET core source code for System.Linq.Expressions , I found the following code located here : Is there any way that GetGetMethod and GetSetMethod can both return null , as seems to be accounted for here ? Is this dead code ? The C # compiler does n't allow for a property to have no getter and no setter , s... | MethodInfo mi = property.GetGetMethod ( true ) ; if ( mi == null ) { mi = property.GetSetMethod ( true ) ; if ( mi == null ) { throw Error.PropertyDoesNotHaveAccessor ( property , nameof ( property ) ) ; } } | Can a C # Property ever have no GetMethod and no SetMethod |
C# | Im still pretty new so bear with me on this one , my question ( s ) are not meant to be argumentative or petty but during some reading something struck me as odd.Im under the assumption that when computers were slow and memory was expensive using the correct variable type was much more of a necessity than it is today .... | for ( int i = 0 ; i < length ; i++ ) | Using different numeric variable types |
C# | I have application and I have to use a certificate which requires a pin from prompt window.I have following code.Everything works fine in console application but when I run that code in windows service or console application started from task scheduler then application freezes on that line.No exceptions , no progress.I... | SecureString password = GetPassword ( ) ; X509Certificate2 certificate = GetCertificate ( ) ; var cspParameters = new CspParameters ( 1 , `` ProviderName '' , `` KeyContainerName '' , null , password ) ; certificate.PrivateKey = new RSACryptoServiceProvider ( cspParameters ) ; certificate.PrivateKey = new RSACryptoServ... | Setting private key in certificate hangs windows service |
C# | Question is simpleis this codesame fast as this codecommon sense tell me that it should be faster to look up the reference in dictionary once and store it somewhere so that it does n't need to be looked up multiple times , but I do n't really know how dictionary works.So is it faster or not ? And why ? | public Dictionary < string , SomeObject > values = new Dictionary < string , SomeObject > ( ) ; void Function ( ) { values [ `` foo '' ] .a = `` bar a '' ; values [ `` foo '' ] .b = `` bar b '' ; values [ `` foo '' ] .c = `` bar c '' ; values [ `` foo '' ] .d = `` bar d '' ; } public Dictionary < string , SomeObject > ... | Is it faster to copy reference to object from dictionary or access it directly from dictionary ? |
C# | I have tested two rescaling functions by applying them on FFT convolution outputs.The first one is collected from this link.Here the problem is incorrect contrast.The second one is collected from this link.Here the output is totally white.So , you can see two of the versions are giving one correct and another incorrect... | public static void RescaleComplex ( Complex [ , ] convolve ) { int imageWidth = convolve.GetLength ( 0 ) ; int imageHeight = convolve.GetLength ( 1 ) ; double maxAmp = 0.0 ; for ( int i = 0 ; i < imageWidth ; i++ ) { for ( int j = 0 ; j < imageHeight ; j++ ) { maxAmp = Math.Max ( maxAmp , convolve [ i , j ] .Magnitude ... | Rescaling Complex data after FFT Convolution |
C# | I have code like this : Let 's say the LongRunningCalc methods each take 1 second . The code above takes about 2 seconds to run , because while the list of 5 elements is operated on in parallel , the two methods called from the let statements are called sequentially.However , these methods can safely be called in paral... | var list = new List < int > { 1 , 2 , 3 , 4 , 5 } ; var result = from x in list.AsParallel ( ) let a = LongRunningCalc1 ( x ) let b = LongRunningCalc2 ( x ) select new { a , b } ; | How to run LINQ 'let ' statements in parallel ? |
C# | Consider the following two extension methods : When I wrote my second method , I intended it to call the generic LINQ Enumerable.Contains < T > method ( type arguments inferred from the usage ) . However , I found out that it is actually calling the first method ( my custom Contains ( ) extension method . When I commen... | using System ; using System.Collections.Generic ; using System.Linq ; public static class Extensions { public static bool Contains ( this IEnumerable self , object obj ) { foreach ( object o in self ) { if ( Object.Equals ( o , obj ) ) { return true ; } } return false ; } public static bool ContainsEither < T > ( this ... | Why does the compiler choose overload with IEnumerable over IEnumerable < T > ? |
C# | I have a view model which retrieves an object from some service , and makes it available for data binding . The object is implementing INotifyPropertyChanged . In the view model , I am listening to the PropertyChanged event to perform some internal actions when certain properties in the object are modified.Now it is po... | public class MyViewModel : INotifyPropertyChanged { private DataType myData ; public DataType MyData { get { return myData ; } protected set { if ( value == myData ) return ; if ( myData ! = null ) myData.PropertyChanged -= DataPropertyChanged ; myData = value ; myData.PropertyChanged += DataPropertyChanged ; OnNotifyP... | Is unsubscribing from event necessary for an object with shorter lifetime ? |
C# | In C , when compiled to a x86 machine , I would usually replace branches with logical expression , when speed is the most important aspect , even if the conditions are complex , for example , instead ofI will write : Now clearly , this might be a harder to maintain , and less readable code , but it might actually be fa... | char isSomething ( ) { if ( complexExpression01 ) { if ( complexExpression02 ) { if ( ! complexExpression03 ) { return 1 ; } } } return 0 ; } char isSomething ( ) { return complexExpression01 & & complexExpression02 & & ! complexExpression03 ; } | Avoiding branches in managed languages |
C# | This is just for academic purpose . I noticed that for integral literals , we can declare up to 18446744073709551615 which is 2^64-1 or ulong.MaxValue . Defining greater than this value produces a compile-time error . And for floating-point literals , we can declare them with integral part up to 999 ... 999 ( 9 is repe... | namespace FloatingPoint { class Program { static void Main ( string [ ] args ) { const ulong @ ulong = 18446744073709551615 ; const double @ double = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999... | C # compiler does not limit the number of digits of fractional part of a floating-point literal |
C# | I 'm trying to post to a local bitcoin full node via json-rpc but I 'm getting an error from the server.Following the documentation here : https : //bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/createrawtransaction/I can see the following example structure for a createrawtransaction request : My code creates the f... | { `` jsonrpc '' : `` 1.0 '' , `` id '' : '' curltest '' , `` method '' : `` createrawtransaction '' , `` params '' : [ `` [ { \ '' txid\ '' : \ '' myid\ '' , \ '' vout\ '' :0 } ] '' , `` [ { \ '' address\ '' :0.01 } ] '' ] } { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' createrawtransaction '' , ... | Trouble posting CREATERAWTRANSACTION to Bitcoin Core via JSON-RPC |
C# | Given an enum like this : I am using the following code to give me an IEnumerable : The code works very good however I have to do this for quite a lot of enums . Is there a way I could create a generic way of doing this ? | public enum City { London = 1 , Liverpool = 20 , Leeds = 25 } public enum House { OneFloor = 1 , TwoFloors = 2 } City [ ] values = ( City [ ] ) Enum.GetValues ( typeof ( City ) ) ; var valuesWithNames = from value in values select new { value = ( int ) value , name = value.ToString ( ) } ; | How can I use Generics to create a way of making an IEnumerable from an enum ? |
C# | I have something like this : Why is Math.Round ( ) rounding even numbers down and odd numbers up ? | double d1 = Math.Round ( 88.5 , 0 ) ; // result 88double d2 = Math.Round ( 89.5 , 0 ) ; // result 90 | Rounding up and down by Math Round ( ) |
C# | I am working on a legacy ecommerce platform and have noticed a convention when dealing with credit card numbers . C # or in sqlI presume the reasoning is to remove it from memory before setting it to null which may not remove the value . But that reasoning would seem to suggest that SQL Server and/or the .NET VM had vu... | cardnumber = `` 11111111111111111111 '' ; cardnumber = null ; update cards set cardnumber = '11111111111111111111 ' where customerid = @ CustomerIDupdate cards set cardnumber = null where customerid = @ CustomerID | Overwrite then set to null |
C# | The following results do n't make any sense to me . It looks like a negative offset is cast to unsigned before addition or subtraction are performed.Although it might seem strange to use negative offsets , there are use cases for it . In my case it was reflecting boundary conditions in a two-dimensional array.Of course... | double [ ] x = new double [ 1000 ] ; int i = 1 ; // for the overflow it makes no difference if it is long , int or shortint j = -1 ; unsafe { fixed ( double* px = x ) { double* opx = px+500 ; // = 0x33E64B8 //unchecked // { double* opx1 = opx+i ; // = 0x33E64C0 double* opx2 = opx-i ; // = 0x33E64B0 double* opx3 = opx+j... | Pointer offset causes overflow |
C# | I have a situation where I need to dynamically build up a list of filters to apply to a list of objects . Those objects can be anything that implements an interface which contains all of the properties I need to filter on.I have a list of criteria defined like so ... and add criteria like so ... I then apply the criter... | public interface IStuff { bool SuitableForSomething { get ; set ; } bool SuitableForSomethingElse { get ; set ; } } public class SomeStuff : IStuff { ... } public class SomeOtherStuff : IStuff { ... } public List < Expression < Func < IStuff , bool > > > Criteria { get ; private set ; } Criteria.Add ( x = > x.SuitableF... | C # generic constraint not working as expected |
C# | I want to build my grammar to accept multiple number . It has a bug when I repeat the number like saying 'twenty-one ' . So I kept reducing my code to find the problem . I reached the following piece of code for the grammar builder : Now when I pronounce `` one one '' it still gives me this exception Which when I googl... | string [ ] numberString = { `` one '' } ; Choices numberChoices = new Choices ( ) ; for ( int i = 0 ; i < numberString.Length ; i++ ) { numberChoices.Add ( new SemanticResultValue ( numberString [ i ] , numberString [ i ] ) ) ; } gb [ 1 ] .Append ( new SemanticResultKey ( `` op1 '' , ( GrammarBuilder ) numberChoices ) ... | TargetInvocationException when using SemanticResultKey |
C# | a few months ago I wrote this code because it was the only way I could think to do it ( while learning C # ) , well . How would you do it ? Is unchecked the proper way of doing this ? | unchecked //FromArgb takes a 32 bit value , though says it 's signed . Which colors should n't be . { _EditControl.BackColor = System.Drawing.Color.FromArgb ( ( int ) 0xFFCCCCCC ) ; } | How to do this without unchecked ? |
C# | My C # code uses impersonation by calling Win32 functions via P/Invokealso I have AppDomain.CurrentDomain.UnhandledException handler installed that also logs all unhandled exception.I 'm sure that the code that logs exceptions works fine both with and without impersonation.Now the problem is that in the above code it l... | internal class Win32Native { [ DllImport ( `` advapi32.dll '' , SetLastError = true ) ] public static extern int ImpersonateLoggedOnUser ( IntPtr token ) ; [ DllImport ( `` advapi32.dll '' , SetLastError = true ) ] public static extern int RevertToSelf ( ) ; } try { var token = obtainTokenFromLogonUser ( ) ; Win32Nativ... | Why is exception from impersonated code not caught ? |
C# | I was reading Pulling the switch here and came across this code . Can somoone please explain what is ( ) = > { } and what should I read up to understand that line of code ? | var moveMap = new Dictionary < string , Action > ( ) { { `` Up '' , MoveUp } , { `` Down '' , MoveDown } , { `` Left '' , MoveLeft } , { `` Right '' , MoveRight } , { `` Combo '' , ( ) = > { MoveUp ( ) ; MoveUp ( ) ; MoveDown ( ) ; MoveDown ( ) ; } } } ; moveMap [ move ] ( ) ; | What does ( ) = > { } mean ? |
C# | I want to specify that one property in an XML serializable class is an attribute of another property in the class , not of the class itself . Is this possible without creating additional classes ? For example , if I have the following C # classhow can I specify that IsAlertOneEnabled is an attribute of AlertOne so that... | class Alerts { [ XmlElement ( `` AlertOne '' ) ] public int AlertOneParameter { get ; set ; } public bool IsAlertOneEnabled { get ; set ; } } < Alerts > < AlertOne Enabled= '' True '' > 99 < /AlertOne > < /Alerts > | How to specify one property is attribute of another In C # XML serialization ? |
C# | So I have a simple enough console app : I 've built it with release configuration . When I run it and open task manager , I see ithas 4 threads . Why is this happening even though I 'm not creating any threads ? This ca n't possibly be each application . I tried opening notepad and it has just 1 thread . Although it is... | class Program { static void Main ( string [ ] args ) { Console.ReadKey ( ) ; } } | Free multiple threads ? |
C# | I have an interface to a .NET service layer , which , in turn , will communicate with a third-party system via a web service . This handles a number of different tasks related to the third-party system 's functionality ( it is actually a bespoke CRM system , but as the context is n't relevant I will swap this out for s... | public interface IMyService { CarModel GetCar ( string registration ) ; CarModel AddCar ( Car car ) ; PersonModel GetPerson ( string personId ) ; PersonModel AddPerson ( Person person ) ; } public class BaseResponseModel { public List < string > Errors { get ; set ; } public bool HasErrors { get { return ( Errors ! = n... | Generics and convention in C # |
C# | For some reason this statement is working fine : But if at the top of the class , I define an alias ( to save space ) : Then the resulting line of code : Gives me an error : '' Delegate 'System.Func < ValidationMessage , int , bool > ' does not take 1 arguments '' . What 's odd about that is that is n't the Delegate I ... | vms.Where ( vm = > vm.MessageType == ValidationMessage.EnumValidationMessageType.Warning ) using MsgType = ValidationMessage.EnumValidationMessageType ; vms.Where ( vm = > vm.MessageType == MsgType.Warning ) | Using a type alias in a linq statement is generating an error |
C# | ProblemI currently have a factory that depends on a few parameters to properly decide which object to return . This factory is not yet bound to DI . As I understand it NInject uses providers as a factory.Here is what I currently have . I 'll warn you it 's not pretty.I 'm almost certain this is not the proper way of dy... | public interface IRole { string Name { get ; } } public class FooRole : IRole { public string Name { get { return `` Foo Role '' ; } } } public class BarRole : IRole { public string Name { get { return `` Bar Role '' ; } } } public class FooBarRoleModule : NinjectModule { public override void Load ( ) { Bind < IRole > ... | Dynamically determining dependency based on user parameters |
C# | I 'm trying to understand the yield keyword better and I think I have a decent enough understanding of it so I ran some tests however I was surpised by the results.If I run the below code I get the following output which shows that it loops over the whole range not just up to number 4.Output : If I run the below code i... | public void DoIt ( ) { Console.WriteLine ( `` Method Call '' ) ; var results = GetData ( Enumerable.Range ( 1 , 10 ) ) ; Console.WriteLine ( `` LINQ '' ) ; var filtered = results.Where ( x = > x == 4 ) ; Console.WriteLine ( `` Start result loop '' ) ; foreach ( var item in filtered ) { Console.WriteLine ( `` Item is ``... | Understanding the yield keyword and LINQ |
C# | Let 's say we have a Foo class : For you to gain perspective , I can say that data in these files has been recorded for about 2 years at frequency of usually several Foo 's every minute.Now : we have a parameter called TimeSpan TrainingPeriod which is about 15 days for example . What I 'd like to accomplish is to call ... | public class Foo { public DateTime Timestamp { get ; set ; } public double Value { get ; set ; } // some other properties public static Foo CreateFromXml ( Stream str ) { Foo f = new Foo ( ) ; // do the parsing return f ; } public static IEnumerable < Foo > GetAllTheFoos ( DirectoryInfo dir ) { foreach ( FileInfo fi in... | Split an single-use large IEnumerable < T > in half using a condition |
C# | In a lot of TDD tutorials I see code like this : This all makes sense but at some point you are going to get to the class that actually uses MyClass and you want to test that the exception is handled : So why not put the try/catch in MyClass in the first place rather than throwing the exception and have the test that t... | public class MyClass { public void DoSomething ( string Data ) { if ( String.IsNullOrWhiteSpace ( Data ) ) throw new NullReferenceException ( ) ; } } [ Test ] public DoSomething_NullParameter_ThrowsException ( ) { var logic = MyClass ( ) ; Assert.Throws < NullReferenceException > ( ( ) = > logic.DoSomething ( null ) ) ... | Unit Testing and Coding Design |
C# | This is more of a why question . Here it goes.C # 7.0 added a new feature called `` Local Function '' . Below is a code snippet.What I dont understand is , its doing a recursive call to the same method . We can easily achieve this with a normal foreach . Then why a local function . MSDN says methods implemented as iter... | public int Fibonacci ( int x ) { if ( x < 0 ) throw new ArgumentException ( `` Less negativity please ! `` , nameof ( x ) ) ; return Fib ( x ) .current ; ( int current , int previous ) Fib ( int i ) { if ( i == 0 ) return ( 1 , 0 ) ; var ( p , pp ) = Fib ( i - 1 ) ; return ( p + pp , p ) ; } } | How is local function in C # 7.0 different from a foreach or a loop ? |
C# | For example I have these two lists : How can I concatenate firstName [ 0 ] and lastName [ 0 ] , firstName [ 1 ] and lastName [ 1 ] , etc and put it in a new list ? | List < string > firstName = new List < string > ( ) ; List < string > lastName = new List < string > ( ) ; | Merging 2 Lists |
C# | I ran into this statement in a piece of code : colorList is a list of class System.Drawing.Color.Now the statement is supposed to retrieve the median index of the list .. like the half point of it .. but I ca n't understand how that > > symbol works and how the `` 1 '' is supposed to give the median index .. I would ap... | Int32 medianIndex = colorList.Count > > 1 ; | What does the `` > > '' operator in C # do ? |
C# | I found article stating that recycling and reusing variables is good practice in unity . So I adopted it.But one thing not clear : does this apply to value type variables ( integers , vectors ) ? is there a point i using this : instead of this : | int x ; Vector3 v ; void functionCalledVeryOften ( ) { x=SomeCalculation ( ) ; v=SomeCalc ( ) ; //do something with x and v } void functionCalledVeryOften ( ) { int x=SomeCalculation ( ) ; Vector3 v=SomeCalc ( ) ; //do something with x and v } | is there a point in recycling value types unity |
C# | I have a TreeView that is filled with different types of items . The items can either be of type Node ( then they may have children ) or of type Entry ( then they do n't have children ) . For that , I bound my TreeView to my ViewModel property AllNodesAndEntries which is an ObservableCollection < object > . For differe... | < TreeView ItemsSource= '' { Binding AllNodesAndEntries } '' > < TreeView.Resources > < HierarchicalDataTemplate ItemsSource= '' { Binding Children } '' DataType= '' { x : Type local : Node } '' > < TextBlock Text= '' { Binding Name } '' Background= '' LightBlue '' / > < /HierarchicalDataTemplate > < DataTemplate DataT... | Disable focusability of certain entries in TreeView |
C# | So i convert a float to a string , which is formatted as a currency.But when I want to convert it back to a float , it would n't be possible , because a float cant store the € symbol . So is there a way to convert the string back to a float , but it disregards the `` € '' ( with the space ) ? | float f = 2.99F ; string s = f.ToString ( `` c2 '' ) ; //s = 2.99 € | How to parse a string to a float , without the currency format ? |
C# | I am trying to write unit tests for a new project I have created and I 've run into an issue where I ca n't work out how a class that I am intending to write is actually testable . Below I 've simplified the class that I am trying to write to give you an idea of what I am trying to achieve.So I have an XML parser that ... | public UserDetails ParseUserDetails ( string request , string username , string password ) { var response = new XmlDocument ( ) ; response.Load ( string.Format ( request + `` ? user= { 0 } & password= { 1 } '' , username , password ) ) ; // Validation checks return new UserDetails { // Populate object with XML nodes } ... | Should all classes be testable ? |
C# | Sorry to ask this as I thought I knew the answer , I want to exit the program if userName is greater than 4 characters or userName is not an account called student . However this even if the userName is only 3 characters and is not student I 'm still hitting Application.Exit . What am I doing wrong ? Shame on me : - ( | if ( userName.Length > 4 | userName ! = `` student '' ) { Application.Exit ( ) ; } | C # simple IF OR question |
C# | An interesting question arose today . Let 's say I have a .NET object that implements a certain interface IMyInterface and is also COM Visible.Now , I load the type from its ProgID and cast to a strongly-typed interface , like so : If I execute the above code , when objEarlyBound.Method ( ) executes , am I calling into... | IMyInterface objEarlyBound = null ; Type t = Type.GetTypeFromProgID ( `` My.ProgId '' ) ; objLateBound = Activator.CreateInstance ( t ) ; objEarlyBound= ( IMyInterface ) objLateBound ; objEarlyBound.Method ( ) ; | Am I calling a .NET object or a COM object ? |
C# | ExpertsI would like to shuffle windows forms automatically every after 5 mins . windows forms contains Multiple querys , Multiple videos , Multiple powerpoints.I am having three windows forms , as follows.Forms 1 code : Forms 2 : Microsoft Powerpoint filemultiple powerpoint files from network folder ( path ) Forms 3 : ... | using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace Daily_System { public partial class Form1 : Form { public Form1 ( ) { InitializeCompone... | Auto shuffle between windows forms every after 5 min |
C# | This is not a biggie at all , but something that would be very helpful indeed if resolved . When I 'm overloading methods etc there are times when the xml comments are exactly the same , bar 1 or 2 param names . I have to copy/paste the comments down to each overloaded method , where they are the same . Sometimes , how... | /// < summary > /// Go and do something /// < /summary > public void DoSomething ( ) { DoSomething ( true , `` Done something '' ) ; } /// < summary > /// Go and do something /// < /summary > /// < param name= '' doIt '' > whether it should be done or not < /param > public void DoSomething ( bool doIt ) { DoSomething (... | Is there a way of referencing the xml comments to avoid duplicating them ? |
C# | We recently updated our applications to make use of SHA-256 code-signing with a new certificate . The assemblies are strong name signed using the Sign the assembly option in Visual Studio 2015 . The post build event in Visual Studio runs two signtool.exe processes to sign both in SHA-256 and for the legacy SHA-1 certif... | call `` C : \Program Files ( x86 ) \Windows Kits\10\bin\x86\signtool.exe '' sign /f `` < mystrongName.pfx > '' /p `` < password > '' /t < timestampURL > `` $ ( TargetPath ) '' call `` C : \Program Files ( x86 ) \Windows Kits\10\bin\x86\signtool.exe '' sign /f `` < mystrongName.pfx > '' /p `` < password > '' /fd sha256 ... | Air-gapped .NET code-signed application will not install/run |
C# | So I have this 2 methods which suppose to multiply a 1000 items long array of integers by 2.The first method : The second method : Note that I use this code only for performance research and that 's why it looks so disgusting.The surprising result is that Power is faster by almost 50 % than PowerNoLoop even though I ha... | [ MethodImpl ( MethodImplOptions.NoOptimization ) ] Power ( int [ ] arr ) { for ( int i = 0 ; i < arr.Length ; i++ ) { arr [ i ] = arr [ i ] + arr [ i ] ; } } [ MethodImpl ( MethodImplOptions.NoOptimization ) ] PowerNoLoop ( int [ ] arr ) { int i = 0 ; arr [ i ] = arr [ i ] + arr [ i ] ; i++ ; arr [ i ] = arr [ i ] + a... | Weird performance behavior |
C# | Have an app where I would like to upload an image . I am using byte array for this.The image is required but when I put that annotation on the variable and try create an image , it gives me the error message when it should have the image there . It also returns that the Model is Invalid.When I remove the Required , it ... | [ Key ] public int InvoiceId { get ; set ; } [ Required ( ErrorMessage = `` Company is required '' ) ] public string Company { get ; set ; } [ Required ( ErrorMessage = `` Description is required '' ) ] public string Description { get ; set ; } [ Required ( ErrorMessage = `` Amount is required '' ) ] public decimal Amo... | Can not make Byte a Required Field |
C# | How does one add a new function to a delegate without using the += notation ? I wonder how to do his from another CLR langage , namely F # . ( I know there are much nicer way to deal with events in F # , but I am being curious.. ) Edit As pointed out by Daniel in the comments , the fact that one has no direct way of do... | static int Square ( int x ) { return x * x ; } static int Cube ( int x ) { return x * x * x ; } delegate int Transformer ( int x ) ; Transformer d = Square ; d += Cube ; | Adding delegate in C # |
C# | Given the class below , to launch a splash screen on an alternate thread : This is called and closed with the following respective commands Fine.I am not exactly new to the TPL , of course we can show the form on another thread using something as simple as : My issue is closing this SomeForm down when you are ready . T... | public partial class SplashForm : Form { private static Thread _splashThread ; private static SplashForm _splashForm ; public SplashForm ( ) { InitializeComponent ( ) ; } // Show the Splash Screen ( Loading ... ) public static void ShowSplash ( ) { if ( _splashThread == null ) { // Show the form in a new thread . _spla... | TPL Equivalent of Thread Class 'Splash-Type ' Screen |
C# | I am using an expression to identify a specific method in a class , and return the attribute of the method . When the method is async , the compiler gives me a warning that the method should be awaited.Are there any other ways I could identify the method , or any way to suppress the warning , without using pragma ? I w... | class Program { static void Main ( string [ ] args ) { var attributeProvider = new AttributeProvider ( ) ; var attributeText = attributeProvider.GetAttribute < Program > ( p = > p.MethodA ( ) ) ; //Warning : Because this call is not awaited , ... } [ Text ( `` text '' ) ] public async Task < string > MethodA ( ) { retu... | Expressions to identify async methods causes compiler warning |
C# | I 'm porting a Win8.1 app to UWP for Win10 and experiencing a strange issue with the AppBar . We 've tried using CommandBar instead of AppBar , but the issue still occurs for us . We 're on the latest version of MyToolkit ( 2.5.16 as of this writing ) . Our views are derived like so : SomeView derives from BaseView der... | < views : BaseView x : Name= '' pageRoot '' x : Class= '' OurApp.HomeView '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.open... | Why does my AppBar appear as ClosedDisplayMode.Compact on Page load regardless of actual setting ? |
C# | What does the @ sign does when inserted in front of parameters SQL query ? for example : | using ( SqlCommand cmd = new SqlCommand ( `` INSERT INTO [ User ] values ( @ Forename , @ Surname , @ Username , @ Password ) '' , con ) ) { cmd.Parameters.AddWithValue ( `` @ Forename '' , txtForename.Text ) ; cmd.Parameters.AddWithValue ( `` @ Surname '' , txtSurname.Text ) ; cmd.Parameters.AddWithValue ( `` @ UserNa... | What does the @ in front of a parameter name do ? |
C# | I know a lot has been written about Linq and it 's inner workings . Inspired by Jon Skeets EduLinq , I wanted to to demystify what 's going on behind the Linq Operators . So what I tried to do is to implement Linqs Select ( ) method which sounds pretty boring at first sight . But what I 'm actually trying to do is to i... | class Program { static void Main ( string [ ] args ) { var list = new int [ ] { 1 , 2 , 3 } ; var otherList = list.MySelect ( x = > x.ToString ( ) ) .MySelect ( x = > x + `` test '' ) ; foreach ( var item in otherList ) { Console.WriteLine ( item ) ; } Console.ReadLine ( ) ; } } public static class EnumerableEx { publi... | Implementing Linqs Select without the yield keyword . Ca n't follow the control flow |
C# | I have an total amount payable by an Employer this amount needs to be split amongst staff.For exampleThe total amount payable is the sum of all items , in this case $ 400The problem is I must call a 3rd party system to assign these amounts one by one . But I can not let the balance go below $ 0 or above the total amoun... | a $ 100b $ 200c - $ 200d - $ 200e $ 500 a $ 100b $ 200e $ 500c - $ 200d - $ 200 | Allocate money in particular order |
C# | I just stumbled upon this fragment of code , I was wondering why the Count is done during the loop.If the count can change , shouldn ’ t we just do it like this instead : for ( int i = source.Count ( ) - 1 ; i > = 0 ; i -- ) Otherwise , I think we should calculate the count before the looping starts , instead of every ... | /// < summary > /// find the first index in a sequence to satisfy a condition /// < /summary > /// < typeparam name= '' T '' > type of elements in source < /typeparam > /// < param name= '' source '' > sequence of items < /param > /// < param name= '' predicate '' > condition of item to find < /param > /// < returns > ... | IEnumerable.Count ( ) O ( n ) |
C# | Consider this code : Inside the function , I want to know if a value has been sent to Variable1 & Variable2 , prior to the function call , even if the DEFAULT values have been sent , that 's ok ( null for string & 0 for int ) | public string Variable1 { get ; set ; } public int Variable2 { get ; set ; } public void Function ( ) { // Has been Variable1 Initialized ? } | Ensure Variable Initialization C # |
C# | When I am using this code as web view , it works fine , but when with developer option in Chrome I select Mobile View , FormCollection shows empty strings in the controllerVIEW ( Edit updtaed ) ControllerNormal View ( Web View ) Mobile View | < div class= '' page product-details-page deal-product-details-page '' > @ using ( Html.BeginForm ( `` AddProductToCart_Details '' , `` DealProduct '' , new { productId = Model.Id , shoppingCartTypeId = 1 } , FormMethod.Post ) ) { < div class= '' page-body '' > @ using ( Html.BeginRouteForm ( `` Product '' , new { SeNa... | FormCollection Empty in ASP.NET Mobile View |
C# | I 'm trying to write generic algorithms in C # that can work with geometric entities of different dimension . In the following contrived example I have Point2 and Point3 , both implementing a simple IPoint interface.Now I have a function GenericAlgorithm that calls a function GetDim . There are multiple definitions of ... | interface IPoint { public int NumDims { get ; } } public struct Point2 : IPoint { public int NumDims = > 2 ; } public struct Point3 : IPoint { public int NumDims = > 3 ; } class Program { static int GetDim < T > ( T point ) where T : IPoint = > 0 ; static int GetDim ( Point2 point ) = > point.NumDims ; static int GetDi... | C # generics method selection |
C# | I have a list of sorts stored in this format : And I need to turn it into a lambda expression of type Action < DataSourceSortDescriptorFactory < TModel > > So assuming I have the following collection of Report Sorts as : I would need to transform it into such a statement to be used like so : And the sort method signatu... | public class ReportSort { public ListSortDirection SortDirection { get ; set ; } public string Member { get ; set ; } } new ReportSort ( ListSortDirection.Ascending , `` LastName '' ) , new ReportSort ( ListSortDirection.Ascending , `` FirstName '' ) , .Sort ( sort = > { sort.Add ( `` LastName '' ) .Ascending ( ) ; sor... | Dynamically build lambda expression from a collection of objects ? |
C# | I have two similar methods that basically does the same thing only with different objects.What 's the best way to make a generic method out of this if possible ? The two objects : The two methods that I potentially want to make into a generic : I must note that : - I have no control over how the table fields are named ... | public class StoreObject { int Key ; string Address ; string Country ; int Latitude ; int Longitude ; } public class ProjectObject { int ProjectKey ; string Address ; string Description ; } public StoreObject GetStoreByKey ( int key ) { using ( DBEntities dbe = new DBEntities ( ) ) { StoreObject so = new StoreObject ( ... | How to create a generic method out of two similar yet different methods ? |
C# | According to the Best Practices section of the MSDN documentation for the System.Enum class : Do not define an enumeration value solely to mirror the state of the enumeration itself . For example , do not define an enumerated constant that merely marks the end of the enumeration . If you need to determine the last valu... | public enum DrawOrder { VeryBottom = 0 , Bottom = 1 , Middle = 2 , Top = 3 , Lowest = VeryBottom , //marks a position in the enum Highest = Top , //marks a position in the enum } | Why are position markers , like first or last , in an Enumeration considered bad practice ? |
C# | I am new to .Net Framework and I want to add validations to my windows form application in Visual Studio 2010 IDE . I have searched for different ways to do it but I am not sure where can i add that code in my form ? One of the example being the code below . Do I add this code on form load method or on submit button or... | using System ; using System.Data.Entity ; using System.ComponentModel.DataAnnotations ; namespace MvcMovie.Models { public class Movie { public int ID { get ; set ; } [ Required ( ErrorMessage = `` Title is required '' ) ] public string Title { get ; set ; } [ Required ( ErrorMessage = `` Date is required '' ) ] public... | Validating my form |
C# | This question has been bugging me for a while : I 've read in MSDN 's DirectX article the following : The destructor ( of the application ) should release any ( Direct2D ) interfaces stored ... Now , if all of the application 's data is getting released/deallocated at the termination ( source ) why would I go through t... | DemoApp : :~DemoApp ( ) { SafeRelease ( & m_pDirect2dFactory ) ; SafeRelease ( & m_pRenderTarget ) ; SafeRelease ( & m_pLightSlateGrayBrush ) ; SafeRelease ( & m_pCornflowerBlueBrush ) ; } | Cleanup before termination ? |
C# | I thought the method that is getting called is decided runtime , or have I missed something ? Sample code : I thought I would get : as output but it prints Base impl . Is there anything I can do to get the overloaded method without casting the input ? | class Program { static void Main ( string [ ] args ) { var magic = new MagicClass ( ) ; magic.DoStuff ( new ImplA ( ) ) ; magic.DoStuff ( new ImplB ( ) ) ; Console.ReadLine ( ) ; } } class MagicClass { internal void DoStuff < T > ( T input ) where T : SomeBase { HiThere ( input ) ; } void HiThere ( SomeBase input ) { C... | Why is n't the overloaded method getting called ? |
C# | Starting from C # 7.0 the throw keyword can be used both as an expression and as a statement , which is nice.Though , consider these overloadsWhen invoking like thisor even like this ( with a statement lambda ) the M ( Func < > ) overload is selected by the compiler indicating that the throw is here considered as an ex... | public static void M ( Action doIt ) { /*use doIt*/ } public static void M ( Func < int > doIt ) { /*use doIt*/ } M ( ( ) = > throw new Exception ( ) ) ; M ( ( ) = > { throw new Exception ( ) ; } ) ; M ( ( ) = > { throw new Exception ( ) ; return ; } ) ; | How can I force a throw to be a statement and not an expression ( in a lambda expression ) ? |
C# | I come across this regularly when refactoring code . Say I have a base class and I read some configuration parameters and stuff them into properties like this And then I call a method in another class like thisIs it better to do that ? What if I only needed the AppSettings values inside of the OtherClass class ? then I... | public BaseClass ( ) { _property1 = ConfigurationManager.AppSettings [ `` AppSetting1 '' ] ; _property2 = ConfigurationManager.AppSettings [ `` AppSetting2 '' ] ; _property3 = ConfigurationManager.AppSettings [ `` AppSetting3 '' ] ; } OtherClass otherClass = new OtherClass ( ) ; var foo = otherClass.SomeMethod ( _prope... | Passing config values as parameters to an instance method C # |
C# | In all the .NET book I 've read the guide line for implementing events explains that you need to subclass EventArgs and use EventHandler . I looked up more info on http : //msdn.microsoft.com/en-us/library/ms229011.aspx , and it says `` Do use System.EventHandler instead of manually creating new delegates to be used as... | public class IoC { public AbstractFactory GetAbstractFactory ( ) { var factory = new AbstractFactory ( ) ; factory.CreateObject += ( ) = > new object ( ) ; return factory ; } } public class AbstractFactory { public event Func < object > CreateObject ; private object OnObjectCreated ( ) { if ( CreateObject == null ) { t... | Is there a special association between the EventArgs class and the event keyword ? |
C# | I have a problem with this code : I set TermEndDate = DateTime.Now but no message raises ! My test code is : | RuleFor ( field = > field.TermEndDate ) .NotEmpty ( ) .When ( x = > x.TermEndDate == x.TermStartDate ) .WithMessage ( `` error ... '' ) ; var now = DateTime.Now ; var command = new AddTermCommand { SchoolId = Guid.NewGuid ( ) , TermStartDate = now , TermEndDate = now } ; var cmd = command.Validate ( ) ; if ( ! cmd.IsVa... | FluentValidation when does not raises any message |
C# | If I create a .NET class which subscribes to an event with an anonymous function like this : Will this event handler be a root keeping my class from being garbage collected ? If not , wohoo ! But if so , can you show me the removal syntax ? Just using -= with the same code seems wrong . | void MyMethod ( ) { Application.Current.Deactivated += ( s , e ) = > { ChangeAppearance ( ) ; } ; } | Do I need to remove this sort of event handler ? |
C# | I have:1 ) How I may get List < Graph > from database where Points is not empty ? 2 ) How to execute it ? The exception is : LINQ to Entities does not recognize the method ' ... ' method , and this method can not be translated into a store expression . | private Dictionary < int , Сolor [ ] > colorSet = new Dictionary < int , Сolor [ ] > ( ) { { 1 , new Сolor [ 2 ] { Сolor.Red , Сolor.Green } } , { 2 , new Сolor [ 2 ] { Сolor.Yellow , Сolor.Blue } } , ... } ; public class Graph { public Сolor Сolor { get ; set ; } public ICollection < Point > Points { get ; set ; } } L... | C # Linq - get objects with not empty collection |
C# | Consider the following code : Now when I call both generic functions , one succeeds and one fails : Apparently , G.enericFunction2 executes the default operator== implementation instead of my override . Can anybody explain why this happens ? | class CustomClass { public CustomClass ( string value ) { m_value = value ; } public static bool operator == ( CustomClass a , CustomClass b ) { return a.m_value == b.m_value ; } public static bool operator ! = ( CustomClass a , CustomClass b ) { return a.m_value ! = b.m_value ; } public override bool Equals ( object o... | Using overloaded operator== in a generic function |
C# | I happened to read this line of code : Where can I find the document on msdn about the syntax of using `` this '' in property ? And is there any book covers this kind of tricky syntax of C # other than the common stuff ? | public MyArray this [ int index ] { get { return array [ index ] ; } } | What is this syntax : using `` this '' in property in C # ? |
C# | I 'm working on a progress wizard . I defined it as a style based on the ItemsControl . I have an ItemTemplateSelector with two DataTemplates , one for the first item and one for the rest of the items . I have it working correctly except for one really small issue that is super tricky to fix . There is a gap between th... | < Style x : Key= '' WizardProgressBar '' TargetType= '' { x : Type ItemsControl } '' > < Style.Resources > < DataTemplate x : Key= '' FirstItem '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < /Grid.ColumnDefinitions > < Ellipse Name= '' ellipse '' HorizontalAlignment= '' Left '' Heig... | Uniform Grid as Panel Template for All Items in ItemsControl Except the First |
C# | In C # , is it possible to write something like this : I know that the above implementation does not compile , but what I am actually trying to achive is implementing some kind of generic wrapper to an unknown type , so that an client can call the wrapper just as he would call the type , provided by the parameter T , i... | public class MyClass < T > : T where T : class , new ( ) { } | Is it possible to make an object expose the interface of an type parameter ? |
C# | There 's probably 5 or 6 SO posts that tangentially touch on this , but none really answer the question.I have a Dictionary object I use kind of as a cache to store values . The problem is I do n't know how big it is getting -- over time it might be growing big or not , but I can not tell and so I ca n't gauge its effe... | private void someTimer_Tick ( object sender , EventArgs e ) { ... float mbMem = cacheMap.GetMemorySize ( ) ; RecordInLog ( DateTime.Now.ToString ( ) + `` : mbMem is using `` + mbMem.ToString ( ) + `` MB of memory '' ) ; ... } | Logging the memory usage of an object |
C# | Why do explicit C # interface calls within a generic method that has an interface type constraint always call the base implementation ? For example , consider the following code : This code outputs the following : IDerived.Method IBase.MethodInstead of what one might expect : IDerived.Method IDerived.MethodThere seems ... | public interface IBase { string Method ( ) ; } public interface IDerived : IBase { new string Method ( ) ; } public class Foo : IDerived { string IBase.Method ( ) { return `` IBase.Method '' ; } string IDerived.Method ( ) { return `` IDerived.Method '' ; } } static class Program { static void Main ( ) { IDerived foo = ... | Why do explicit interface calls on generics always call the base implementation ? |
C# | I 've two interfaces : And two classes implementing these interfaces like this : When trying to use these classes as shown : I get this compiler error : can not convert from 'ClassB ' to 'IAmB < IAmA > ' I know I can make the compiler happy using : But I need to be able to be the Type parameter for IAmB < > in ClassB a... | public interface IAmA { } public interface IAmB < T > where T : IAmA { } public class ClassA : IAmA { } public class ClassB : IAmB < ClassA > { } public class Foo { public void Bar ( ) { var list = new List < IAmB < IAmA > > ( ) ; list.Add ( new ClassB ( ) ) ; } } public class ClassB : IAmB < IAmA > { } | C # Generics , interfaces and inheritance |
C# | I have the following code in my classThis code works in that when I dispose my class any events that are hooked up to the Received event , will be removed individually.I 've been wondering if rather than being so verbose about it , if the following terse version will have the same effectBasically this comes down to how... | public class Receiver : IReceiver { public event EventHandler Received ; public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) { if ( Received ! = null ) { foreach ( EventHandler delegateMember in Received.GetInvocationList ( )... | Can you use equals assignment when removing delegate members in a disposing method ? |
C# | I was going through the Martin Odersky 's book Programming in Scala with it 's section on abstract modules , and his paper Scalable Component Abstractions : http : //lampwww.epfl.ch/~odersky/papers/ScalableComponent.pdfMy takeaway is that by making your modules abstract classes instead of objects ( or classic static , ... | abstract class myModule { // this is effectively an abstract module , whose concrete // components can be configured by subclassing and instantiating it class thing { } class item { } object stuff { } class element { } object utils { } } | Scala-style abstract modules in C # or other languages ? |
C# | When I insert these values in SqlServer database , the millisecond value changes in a weird wayWhat 's wrong ? Edit : Relevant code : | 09/30/2013 05:04:56.599 09/30/2013 05:04:56.59909/30/2013 05:04:56.59909/30/2013 05:04:57.082 2013-09-30 05:04:56.600 2013-09-30 05:04:56.600 2013-09-30 05:04:56.600 2013-09-30 05:04:57.083 com = new SqlCommand ( ) ; com.Connection = con ; com.CommandText = @ '' INSERT INTO [ AuthSourceTimings ] ( [ FileName ] , [ JobI... | DateTime inserted in SqlServer changes value |
C# | I have a struct that is defined in a COM library.In my ViewModel I have created an observable instance of this , and want to bind each member of the struct to different controls in a view.ConfigStaticDataDetails variable is updated through a delegate in the COM.Is there a way to catch updates to the members of the stru... | public struct ConfigStaticData { public string Callsign ; } private ConfigStaticData _ConfigStaticDataDetails ; public ConfigStaticData ConfigStaticDataDetails { get { return _ConfigStaticDataDetails ; } set { _ConfigStaticDataDetails = value ; OnPropertyChanged ( `` ConfigStaticDataDetails '' ) ; } } < TextBox Name= '... | Can I catch updates to members of an observable struct in WPF ? |
C# | I get very strange behaviour of string.Format . I form message like this : The letters in beginning are in Russian . But then , in calling method , i get this string : Äèñïåò÷åð çàêðûë ñîáûòèå Тревога ( `` Тревога на объекте с точки зрения диспетчера '' ) . This seems like string.Format returned non-unicode characters ... | protected override string GetMessageText ( ManualEventFact reason ) { var messageText = string.Format ( `` Диспетчер закрыл событие { 0 } ( \ '' { 1 } \ '' ) '' , reason.EventTemplate.DisplayName , reason.Text ) ; return messageText ; } | C # String.Format ( ) returns bad characters |
C# | I 'm interested in this part : What 's wrong : One of the parameters of a binary operator must be the containing typeHow I can normaly code this part for mathematic operations ? | public class Racional < T > { private T nominator ; private T denominator ; public T Nominator { get { return nominator ; } set { nominator = value ; } } public T Denominator { get { return denominator ; } set { denominator = value ; } } public Racional ( T nominator , T denominator ) { this.nominator = nominator ; thi... | Help with mathematic operands in class ( c # ) |
C# | I 'm doing a Unity project where I have the need to convert UTM coordinates to latitudes and longitudes . I have tried several C # solutions , but none of them were accurate enough . But I found some Javascript code that gives out the exact result I 'm looking for ( https : //www.movable-type.co.uk/scripts/latlong-utm-... | var a = 6378137 ; var f = 1/298.257223563 ; var e = Math.sqrt ( f* ( 2-f ) ) ; var n = f / ( 2 - f ) ; var n2 = n*n , n3 = n*n2 , n4 = n*n3 , n5 = n*n4 , n6 = n*n5 ; var A = a/ ( 1+n ) * ( 1 + 1/4*n2 + 1/64*n4 + 1/256*n6 ) ; var a = 6378137 ; var f = 1 / 298.257223563 ; var e = Math.Sqrt ( f * ( 2 - f ) ) ; var n = f /... | C # and Javascript code calculations giving different results |
C# | We use ASP.NET core and have this code : After zipping sourceDirectoryName that contains russian symbols if we open this archive with windows explorer , we see the following : and where the name marked with green is correct , and the name marked with red has its name encoding changed.If we use the following code : We h... | public static void Compress ( string sourceDirectoryName , string destinationArchiveFileName ) { var directoryName = Path.GetFileName ( sourceDirectoryName ) ; var remotePath = sourceDirectoryName.Split ( new [ ] { directoryName } , StringSplitOptions.RemoveEmptyEntries ) .First ( ) ; using ( var zipStream = new Memory... | After zipping folder all zip entries change encoding |
C# | When I use a method with a generic parameter to create another object , the generic object is n't selecting the most specific constructor . That sounds confusing , so here 's some sample code to demonstrate what I mean ... Can anyone explain why the output of this program is : ... and how to make the generic Add < T > ... | guid < -- easy - no problem hereobject < -- WHY ? This should also be `` guid '' ? ! void Main ( ) { B b = new B ( ) ; C c = new C ( Guid.Empty ) ; b.Add < Guid > ( Guid.Empty ) ; } public class B { List < C > cs = new List < C > ( ) ; public void Add < T > ( T v ) { cs.Add ( new C ( v ) ) ; } } public class C { public... | Generic method is n't choosing the most specific constructor signature ? |
C# | One of the requirements of the system that I am helping to develop is the ability to import files and we have a set of adapters to process the different types of file ( csv , xml etc . ) we would expect to encounter . During the early part of development we were hard-coding the data adapters via reference and using com... | string dllLocation = @ '' C : MyLocation\dllLocation '' ; DirectoryInfo dir = new DirectoryInfo ( dllLocation ) ; var tempfiles = dir.GetFiles ( `` *Adapter*.dll '' , SearchOption.AllDirectories ) ; // This will need to be changed when we go live foreach ( var file in tempfiles ) { Assembly tempAssembly = null ; //Befo... | Loading more dll 's into code causes crash |
C# | I have a windows media player embedded in my web page view : The ShowMovie action extracts a video stream from the database and sends it to the view with this : When I use a video with a size of about 10K or so will play fine . But if I use a file that is about 137K or so the file never plays . Is it too large ? When I... | < div id= '' divCourseVideo '' style= '' width:100 % ; margin:0 auto ; '' class= '' container '' > < OBJECT style= '' display : inline-block '' ID= '' CoursePlayer '' HEIGHT= '' 400 '' WIDTH= '' 400 '' CLASSID= '' CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6 '' type= '' video/x-ms-wmv '' > < param name='URL ' value= '' @... | WMV streaming file size limit |
C# | I 'd like to know your opinion on a matter of coding style that I 'm on the fence about . I realize there probably is n't a definitive answer , but I 'd like to see if there is a strong preference in one direction or the other.I 'm going through a solution adding using statements in quite a few places . Often I will co... | { log = new log ( ) ; log.SomeProperty = something ; // several of these log.Connection = new OracleConnection ( `` ... '' ) ; log.InsertData ( ) ; // this is where log.Connection will be used ... // do other stuff with log , but connection wo n't be used again } { using ( OracleConnection connection = new OracleConnec... | A question of style/readability regarding the C # `` using '' statement |
C# | In another question , people are getting incomplete data when reading from a HttpWebResponse via GetResponseStream ( ) .I too encountered this problem when reading data from an embedded device which should send me the configuration of 1000 inputs , all in all 32 bytes header and 64 bytes * 1000 resulting in 64032 bytes... | int headerSize = 32 ; int inputSize = 64 ; byte [ ] buffer = new byte [ ( inputSize*1000 ) + headerSize ] ; HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; using ( Stream stream = response.GetResponseStream ( ) ) { if ( stream ! = null ) { stream.Seek ( 0 , SeekOrigin.Begin ) ; stream.Read ( bu... | Why is HttpWebResponse losing data ? |
C# | I am looking into the grammar of C # 5.0 and do n't quite understand the use of `` base '' . In the reference manual , there is a notion of `` base access '' defined as : Where base is a keyword , and it appears that this is the only case . However , I encounter C # inputs such as Can someone point me out which grammar... | base-access : base . identifier base [ expression-list ] base.WithAdditionalDiagnostics < TNode > ( node , diagnostics ) ; | C # grammar `` base '' |
C# | I currently have a class and I am a bit confused with its constructor . what does the statement this ( new BarInterval [ ] { interval } ) imply ? | public class BarListTracker : GotTickIndicator { public BarListTracker ( BarInterval interval ) : this ( new BarInterval [ ] { interval } ) { } } | ` this ` and a class constructor |
C# | I 've read so many articles about this but still I have 2 questions.Question # 1 - Regarding Dependency Inversion : It states that high-level classes should not depend on low-level classes . Both should depend on abstractions . Abstractions should not depend on details . Details should depend on abstractions.for exampl... | public class BirthdayCalculator { private readonly List < Birthday > _birthdays ; public BirthdayCalculator ( ) { _birthdays = new List < Birthday > ( ) ; // < -- -- - here is a dependency } ... public class BirthdayCalculator { private readonly IList < Birthday > _birthdays ; public BirthdayCalculator ( IList < Birthd... | S.O.L.I.D Essentials missing points ? |
C# | I have an enumeration with flags . I want to declare a variable with n different flags . n > 1 in this case.Okay - one variant is to cast each flag into an byte and cast the result to my enum . But this is kinda messy - imho . Is there an more readable way to combine flags ? | public enum BiomeType { Warm = 1 , Hot = 2 , Cold = 4 , Intermediate = 8 , Dry = 16 , Moist = 32 , Wet = 64 , } BiomeType bType = ( BiomeType ) ( ( byte ) BiomeType.Hot + ( byte ) BiomeType.Dry ) | How to combine enumerations with flags ? |
C# | EDIT : I 've done some research about this , but have not been able to find a solution ! I 'm reading a configuration from an XML file.The layout of the configuration is set for certain version.This version is in the first line of the XML , which is easy to extract.What I would like to know is , what is the best way to... | switch ( version.Major ) { case 0 : switch ( version.Minor ) { case 0 : switch ( version.Build ) { case 0 : switch ( version.Revision ) { case 0 : return VersionNone ( doc ) ; } break ; } break ; } break ; } throw new NotImplementedException ( ) ; | Parse file differently upon different version |
C# | I 'm a Java programmer . I have little knowledge on C # . But from the blogs I have read , Java supports only pass-by-value-of-reference whereas in C # the default is pass-by-value-of-reference but the programmer can use pass by reference if needed . I have penned down my understanding of how a swap function works . I ... | public static void Main ( ) { String ONE = `` one '' ; //1 ChangeString ( ONE ) ; //2 Console.WriteLine ( ONE ) ; //3 String ONE = `` ONE '' ; //4 ChangeString ( ref ONE ) ; //5 Console.WriteLine ( ONE ) ; //6 } private static void ChangeString ( String word ) { word = `` TWO '' ; } private static void SeedCounter ( re... | how does a swap method work in C # at a memory level ? |
C# | I 've written a little parsing program to compare the older System.IO.Stream and the newer System.IO.Pipelines in .NET Core . I 'm expecting the pipelines code to be of equivalent speed or faster . However , it 's about 40 % slower.The program is simple : it searches for a keyword in a 100Mb text file , and returns the... | public static async Task < int > GetLineNumberUsingStreamAsync ( string file , string searchWord ) { using var fileStream = File.OpenRead ( file ) ; using var lines = new StreamReader ( fileStream , bufferSize : 4096 ) ; int lineNumber = 1 ; // ReadLineAsync returns null on stream end , exiting the loop while ( await l... | Why is this System.IO.Pipelines code much slower than Stream-based code ? |
C# | I have a user controller created using the hartl tutorial that signs up new users via form with email and password inputs . This is working properly . I am attempting to send an HttpWebRequest from the Unity editor player to my server in order to sign up a new user from a password string created within Unity . I have p... | public static string _url = `` https : //immense-castle-53592.herokuapp.com/signup '' ; HttpWebRequest request = ( HttpWebRequest ) HttpWebRequest.Create ( _url ) ; request.Method = `` POST '' ; request.Headers [ `` action '' ] = `` /users '' ; request.Headers [ `` class '' ] = `` new_user '' ; request.Headers [ `` id ... | How to use Ruby on Rails users controller via Unity ( C # ) to sign up a new user ? |
C# | I need a function which can calculate the mathematical combination of ( n , k ) for a card game . My current attempt is to use a function based on usual Factorial method : It 's working very well but the matter is when I use some range of number ( n value max is 52 and k value max is 4 ) , it keeps me returning a wrong... | static long Factorial ( long n ) { return n < 2 ? 1 : n * Factorial ( n - 1 ) ; } static long Combinatory ( long n , long k ) { return Factorial ( n ) / ( Factorial ( k ) * Factorial ( n - k ) ) ; } long comb = Combinatory ( 52 , 2 ) ; // return 1 which should be actually 1326 | Combinatory issue due to Factorial overflow |
C# | i want to create a windows form which takes image from file and displays in the pictureBox in c # i am having problem when i type image.FromFile after `` = '' the FromFile gets red underline as if it does not consists in the library . | 1 using System ; 2 using System.Collections.Generic ; 3 using System.ComponentModel ; 4 using System.Data ; 5 using System.Drawing ; 6 using System.Linq ; 7 using System.Text ; 8 using System.Windows.Forms ; 9 using System.IO ; 1011 namespace demo212 { 13 public partial class Image : Form14 { 15 public Image ( ) 16 { 1... | .FromFile underlined red and showing error |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.