lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | We use struct in C # whenever possible mainly because it is stored on the stack and no objects are created for it . This boosts the performance.On the other hand , arrays are stored on the heap.My question is , if I include an array as an element of the struct , something as follows : Then what will be the consequences... | struct MotionVector { int [ ] a ; int b ; } | If an array is used as an element in struct ( C # ) , where is it stored ? |
C# | Following is the action that is adding a Loan request to the database : Following is the AddNewLoan ( ) method : And here is the code for Insert ( ) It is adding one row successfully in Loans table but it is also adding rows to LoanProduct and Borrower table as I showed in first code comments.I checked the possibility ... | [ HttpPost ] public ActionResult Add ( Models.ViewModels.Loans.LoanEditorViewModel loanEditorViewModel ) { if ( ! ModelState.IsValid ) return View ( loanEditorViewModel ) ; var loanViewModel = loanEditorViewModel.LoanViewModel ; loanViewModel.LoanProduct = LoanProductService.GetLoanProductById ( loanViewModel.LoanProdu... | Add ( ) method adding duplicate rows for linked models in Code-First Entity Framework |
C# | I 'm currently updating some old code at work . I ran into a number of lines where string.Format ( ) is used for seemingly no reason . I 'm wondering if there is some use for using string.Format ( ) without additional parameters , but I ca n't think of any.What 's the difference between this : and this : I also do n't ... | string query = String.Format ( @ '' select type_cd , type_shpmt from codes '' ) ; string query = `` select type_cd , type_shpmt from codes '' ; | Is there any reason to use string.Format ( ) with just a string parameter ? |
C# | Is this OK : It feels like it might be wrong , but I 'm not sure . | namespace Simple.OData { // Common OData functionality } namespace Simple.Data.OData { // The Simple.Data adapter for OData } | Is it OK to have a namespace name which exists at two points in the tree ? |
C# | I have this piece of VBNet code that i would like to translate into javascript : my translated result : However when i run it it has error Uncaught SyntaxError : Invalid regular expression : : Nothing to repeat ( my VbNet code does n't have any error though ) Does anyone know what 's causing the problem ? | Dim phone_check_pattern = `` ^ ( \+ ? | ( \ ( \+ ? [ 0-9 ] { 1,3 } \ ) ) | ) ( [ 0-9.//- ] |\ ( [ 0-9.//- ] +\ ) ) + ( ( x|X| ( ( e|E ) ( x|X ) ( t|T ) ) ) ( [ 0-9.//- ] |\ ( [ 0-9.//- ] +\ ) ) ) ? $ '' System.Diagnostics.Debug.WriteLine ( System.Text.RegularExpressions.Regex.IsMatch ( `` test input '' , phone_check_pa... | Errors translating regex from .NET to javascript |
C# | I want to insert widgets into my ItemsControl and make them resizeable . How do I achieve this ? This is my XAML : Which binds to : I want to somehow add splitters between items so they can be resized . Is there anything built-in to achieve this ? | < ItemsControl ItemsSource= '' { Binding TestForList , Mode=OneWay } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplate... | Making ItemsControl childs resizeable with a splitter |
C# | I need to do application for Windows Phone for school project . I 've followed tutorial to do RSS reader , but it does n't work and I do n't know why.I 'm getting following error ( after it runs ) : System.Windows.Data Error : BindingExpression path error : 'Items ' property not found on 'Expression.Blend.SampleData.Ju... | public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage ( ) { InitializeComponent ( ) ; this.Loaded += new RoutedEventHandler ( MainPage_Loaded ) ; } public void MainPage_Loaded ( object sender , RoutedEventArgs e ) { WebClient wc = new WebClient ( ) ; wc.OpenReadCompleted += new OpenReadC... | Windows Phone - SyndicationFeed issue |
C# | I 'm facing a requirement to create a static method on my base class , but do n't like that I have to declare type arguments , so I 'm wondering if I 'm going about this the right way.Basically , I 'm assigning delegates that I 'll associate with properties on the class . I could easily put the method on the inherited ... | public class Foo { public string Property1 { get ; set ; } } public class InheritsFoo : Foo { public void AssignDel < TVal > ( Expression < Func < InheritsFoo , TVal > > expr , Action < InheritsFoo , TVal > action ) { } } public static void AssignDel < T , TVal > ( this T source , Expression < T , TVal > > expression ,... | Better way to define static method |
C# | I need a confirmation about a singleton pattern.I 've a singleton class and I 'm using it as dll . I write a program with a reference to this dll and I call my singleton class.I write a second program and I do the same.Am I right if I tell you that even if I have two program they call both a single instance of my singl... | namespace SingletonClassLib { public class SingletonClass { public static int InstanceNumber = 0 ; private static string myName ; # region //Singleton initialisation private SingletonClass ( ) { createInstance ( ) ; } private void createInstance ( ) { InstanceNumber++ ; myName = myName + InstanceNumber.ToString ( ) ; }... | c # singleton class working well confirmation |
C# | I am trying to create an abstract class ( A ) that returns an instance of a generic child of itself ( B ) .I made B 's costructor internal , making the creation of a new instance without my factory impossible , this caused an error I can not seem to find a solution for : ' A.B ' must be a non-abstract type with a publi... | namespace C { class P { static void Main ( ) = > Console.WriteLine ( A.Create < A.B > ( ) .GetType ( ) ) ; } public abstract class A { public class B : A { protected B ( ) { } } public static T Create < T > ( ) where T : A , new ( ) = > new T ( ) ; } } | Factory of inner class objects |
C# | I 'm facing a problem with scene fading . I made a animation of fade in & out also made a script named as Fader which has a coroutine function . Animation works fine . There is also a empty game object named as SceneManager which has a script . In this script button functions are written which open a scene.But the prob... | public class Manager : MonoBehaviour { public void GoBackScene1 ( ) { Fader.instance.Perform ( `` Scene1 '' ) ; } public void Scene2 ( ) { Fader.instance.Perform ( `` Scene2 '' ) ; } public void Scene3 ( ) { Fader.instance.Perform ( `` Scene3 '' ) ; } public void Scene4 ( ) { Fader.instance.Perform ( `` Scene4 '' ) ; }... | Button does n't work correct on scene fading |
C# | Using the code above , is there a way to prevent the Func < int > random = ( ) = > 4 ; line from getting stepped into when debugging ? | private static void Main ( ) { Console.WriteLine ( GetRandomInteger ( ) ) ; Console.ReadLine ( ) ; } [ DebuggerHidden ] private static int GetRandomInteger ( ) { Func < int > random = ( ) = > 4 ; return GetRandomInteger ( random ) ; } [ DebuggerHidden ] private static int GetRandomInteger ( Func < int > random ) { retu... | Preventing lambdas from being stepped into when hosting method is DebuggerHidden |
C# | I have a .Net multi-appdomain application that resembles a scheduler . Default app domain has a timer and a list of jobs that are contained each in it 's own assembly and ran on separate appdomains . Assemblies containing jobs are kept each in it 's separate directory under the application root.Each assembly directory ... | ( root ) \Library\AssemblyName\ domainSetup.PrivateBinPath = @ '' \\Library\\AssemblyName\\ '' | AppDomain dependency resolving order |
C# | I 'm writing a console app that needs to print some atypical ( for a console app ) unicode characters such as musical notes , box drawing symbols , etc.Most characters show up correctly , or show a ? if the glyph does n't exist for whatever font the console is using , however I found one character which behaves oddly w... | Console.Write ( `` ABC '' ) ; Console.Write ( '♪ ' ) ; //This is the same as : Console.Write ( ( char ) 0x266A ) ; Console.Write ( `` XYZ '' ) ; | Why does Console.Write treat character x266A differently ? |
C# | I want to sort a List < string > case sensitive with capitals last , i.e . in the ordera , aBC , b , bXY , c , A , Ax , B , C , ... I have triedbut it returnsA , Ax , B , C , a , aBC , b , bXY , c , ... Is there any predefined method to do this , or will I need to fiddle something together myself ? Edit : Since `` capi... | Comparison < string > c = ( string x1 , string x2 ) = > StringComparer.Ordinal.Compare ( x1 , x2 ) ; list.Sort ( c ) ; | Case sensitive sorting with capitals last |
C# | I have multiple validation boolean properties which can be required or not . If they are required they need to be checked for validation purposes . Therefore I had to build multiple if statements to handle each property . My question is if is there a better way to maintain this instead of having to write if for every n... | public class ProductionNavbarViewModel { public bool IsProductionActive { get ; set ; } public bool ValidatedComponents { get ; set ; } public bool ValidatedGeometries { get ; set ; } public bool ValidatedPokayokes { get ; set ; } public bool ValidatedTechnicalFile { get ; set ; } public bool ValidatedStandardOperation... | C # how to shorten multiple If expressions |
C# | I have a Model-First entity model which contains a Customer table linked to a view that fetches customer details from a separate database . The relationship is One to Many between the Customer table and the View and I have a navigation property on both the Customer entity and the View entity . When I try to perform a d... | Customer selectedCust = ( Customer ) dgvCustomers.SelectedRows [ 0 ] .DataBoundItem ; if ( selectedCust ! = null ) { if ( MessageBox.Show ( String.Format ( `` Are you sure you want to delete Customer { 0 } ? `` , selectedCust.CustomerID.ToString ( ) ) , `` Customer Delete Confirmation '' , MessageBoxButtons.YesNo ) == ... | Deleting Entity Object with 1 to Many Association to View-Based Entity |
C# | I am trying to implement C # 's ExpandoObject-like class in Scala . This is how it is supposed to work : Here is what I have tried so far : When I try to compile this code , I get a StackOverflowError . Please help me get this work . : ) Thanks . | val e = new ExpandoObjecte.name : = `` Rahul '' // This inserts a new field ` name ` in the object.println ( e.name ) // Accessing its value . implicit def enrichAny [ A ] ( underlying : A ) = new EnrichedAny ( underlying ) class EnrichedAny [ A ] ( underlying : A ) { // ... def dyn = new Dyn ( underlying.asInstanceOf ... | Implementing ExpandoObject in Scala |
C# | I have been going crazy trying to read a binary file that was written using a Java program ( I am porting a Java library to C # and want to maintain compatibility with the Java version ) .Java LibraryThe author of the component chose to use a float along with multiplication to determine the start/end offsets of a piece... | int someInt = 1080001175 ; float result = Float.intBitsToFloat ( someInt ) ; // result ( as viewed in Eclipse ) : 3.4923456 int idx = 2025 ; long result2 = ( long ) ( idx * result ) ; // result2 : 7072 int someInt = 1080001175 ; int result = BitConverter.ToSingle ( BitConverter.GetBytes ( someInt ) , 0 ) ; // result : ... | How do I Mimic Number.intBitsToFloat ( ) in C # ? |
C# | For instance , I have this code : VS.Thank you very much for the information . I 'm very excited about learning something new like this . : D | < Grid > < Rectangle Name= '' TheRectangle '' Fill= '' AliceBlue '' Height= '' 100 '' Width= '' 100 '' > < /Rectangle > < /Grid > < Grid > < Rectangle x : Name= '' TheRectangle '' Fill= '' AliceBlue '' Height= '' 100 '' Width= '' 100 '' > < /Rectangle > < /Grid > | I 've recently started learning WPF on my own . What is difference when declaring Name vs. x : Name ? |
C# | The Thread.GetNamedDataSlot method acquires a slot name that can be used with Thread.SetData.Can the result of the GetNamedDataSlot function be cached ( and reused across all threads ) or should it be invoked in/for every thread ? The documentation does not explicitly say it `` should n't '' be re-used although it does... | public Foo { private static LocalStorageDataSlot BarSlot = Thread.GetNamedDataSlot ( `` foo_bar '' ) ; public static void SetMethodCalledFromManyThreads ( string awesome ) { Thread.SetData ( BarSlot , awesome ) ; } public static void ReadMethodCalledFromManyThreads ( ) { Console.WriteLine ( `` Data : '' + Thread.GetDat... | Is it permissible to cache/reuse Thread.GetNamedSlot between threads ? |
C# | I have a problem with converting datetime , I do not see where I make a mistake.I think it should be somewhere to date a date for the same sql query to recognizeThis is the result I get when I set up a break pointThis is the result at the baseThis is my code with which I send the data | var arravialDates = dataAccess.get_dates ( userID , date , DateTime.DaysInMonth ( date.Year , date.Month ) ) ; //get dates for user//working hoursDateTime dateH = new DateTime ( 2099 , 12 , 12 , 0 , 0 , 0 ) ; bool hasDate = false ; for ( int i = 0 ; i < arravialDates.Count ; i++ ) { var arravial = dataAccess.getPraesen... | Convert date into datetime format c # |
C# | Consider : And the IL for Main : First ( IL_000a ) , S : :M ( ) is called with a value type for this . Next ( IL_0011 ) , it 's called with a reference ( boxed ) type.How does this work ? I can think of three ways : Two versions of I : :M are compiled , for value/ref type . In the vtable , it stores the one for ref typ... | interface I { void M ( ) ; } struct S : I { public void M ( ) { } } // in Main : S s ; I i = s ; s.M ( ) ; i.M ( ) ; .maxstack 1.entrypoint.locals init ( [ 0 ] valuetype S s , [ 1 ] class I i ) IL_0000 : nopIL_0001 : ldloc.0IL_0002 : box SIL_0007 : stloc.1IL_0008 : ldloca.s sIL_000a : call instance void S : :M ( ) IL_0... | How does C # handle calling an interface method on a struct ? |
C# | I would like to use a single LINQ aggregate over a collection of ( latitude , longitude ) pairs and produce two ( latitude , longitude ) pairs : I can easily obtain a minimum ( latitude , longitude ) pair by : If possible , I would like to use a single aggregate to return two Locations ; a minimum ( latitude , longitud... | public Location { public double Latitude ; public double Longitude ; } List < Location > border = ... ; var minBorder = border.Aggregate ( new Location ( ) { Latitude = double.MaxValue , Longitude = double.MaxValue } , ( current , next ) = > new Location ( ) { Latitude = ( next.Latitude < current.Latitude ) ? next.Lati... | Is it possible to perform a LINQ aggregate over a collection of one type to a different result type ? |
C# | Following this question Foreach loop for disposing controls skipping iterations it bugged me that iteration was allowed over a changing collection : For example , the following : throws InvalidOperationException : Collection was modified ; enumeration operation may not execute.However in a .Net Form you can do : which ... | List < Control > items = new List < Control > { new TextBox { Text = `` A '' , Top = 10 } , new TextBox { Text = `` B '' , Top = 20 } , new TextBox { Text = `` C '' , Top = 30 } , new TextBox { Text = `` D '' , Top = 40 } , } ; foreach ( var item in items ) { items.Remove ( item ) ; } this.Controls.Add ( new TextBox { ... | Why does ControlCollection NOT throw InvalidOperationException ? |
C# | I come from C++ and find a very different behavior between pointers in C++ and C # .I surprisingly find this code compiles ... And even ... Works perfectly.This make me very puzzled , even in C++ we have a mechanism to protect const objects ( const in C++ almost the same thing as readonly in C # , not const in C # ) , ... | class C { private readonly int x = 0 ; unsafe public void Edit ( ) { fixed ( int* p = & x ) { *p = x + 1 ; } Console.WriteLine ( $ '' Value : { x } '' ) ; } } readonly int* p | Can pointers be used to modify readonly field ? But why ? |
C# | Reading here and here , I understand query syntax and method extensions are pretty much a syntactic difference . But now , I 've a data structure containing measurement data and want determine percentile . I write : and all works fine . ds is of type System.Linq.OrderedEnumerable < double , double > What confuses me is... | var ds = ( from device in dataSet.devices where ! device.paramValues [ i ] .Equals ( double.NaN ) select device.paramValues [ i ] ) .OrderBy ( val = > val ) ; double median = percentile ( ds as IOrderedEnumerable < double > , 0.5 ) ; var ds = ( from device in dataSet.devices where ! device.paramValues [ i ] .Equals ( d... | Linq Query syntax vs . Method Chain : return type |
C# | In T-SQL I have generated UNIQUEIDENTIFIER using NEWID ( ) function . For example : Then , all dashes ( - ) are removed and it looks like this : Now , I need to turn the string above to a valid UNIQUEIDENTIFIER using the following format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and setting the dashes again.To achieve this ... | 723952A7-96C6-421F-961F-80E66A4F29D2 723952A796C6421F961F80E66A4F29D2 SELECT *FROM [ dbo ] . [ RegexMatches ] ( '723952A796C6421F961F80E66A4F29D2 ' , '^. { 8 } |. { 12 } $ | . { 4 } ' ) SELECT *FROM [ dbo ] . [ RegexMatches ] ( '723952A796C6421F961F80E66A4F29D2 ' , '^. { 8 } |. { 4 } | . { 12 } $ ' ) | How regular expression OR operator is evaluated |
C# | Here is my builder interface : And this is my ConcreteBuilder : And the Director is here : And that 's how I am calling it from default page : Now the problem / confusion I am having is how do I pass the Model Data to the concrete classes ? The reason I am confused/stuck is there could be number of different containers... | public interface IContainerBuilder { void SetSections ( ) ; void SetSides ( ) ; void SetArea ( ) ; WebControl GetContainer ( ) ; } public class SingleContainerBuilder : BaseProperties , IContainerBuilder { Panel panel = new Panel ( ) ; public void SetSections ( ) { //panel.Height = value coming from model //panel.Width... | Builder Design Pattern : Accessing/Passing model data to/in Concrete classes |
C# | Considering the following Java code : And now let 's try to do the same in C # The Java example outputI 'm bI 'm bThe C # version outputI 'm aI 'm bIs there a way to implement class b so that it prints `` I 'm b '' twice ? Please notice i 'm not looking at a way to change a . | public class overriding { public static void main ( String [ ] args ) { b b = new b ( ) ; a a = ( a ) b ; a.Info ( ) ; b.Info ( ) ; } } class a { void Info ( ) { System.out.println ( `` I 'm a '' ) ; } } class b extends a { void Info ( ) { System.out.println ( `` I 'm b '' ) ; } } namespace ConsoleApplication2 { class ... | How to achieve same override experience in C # as in Java ? |
C# | I 'm trying to develop an application in moonlight . Now I 'm trying to use a DataGrid to show some data . In an old silverlight project I used a DataGrid in this way : but if I use the same code in my new moonlight project I get an empty page . I 've been looking for some examples and I found a simple one : http : //g... | < UserControl x : Class= '' One.Page '' 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.openxmlformats.org/markup-compatibility/2... | moonlight vs. silverlight : : datagrid incompatibility ? |
C# | Here is my class : Here is my list : If I try and search the list via the `` calculated '' property FullName as follows : I get the following error : System.NotSupportedException : The specified type member 'FullName ' is not supported in LINQ to Entities . Only initializers , entity members , and entity navigation pro... | public class Person { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string FullName { get { return FirstName + `` `` + LastName ; } } } var persons = new List < Person > ( ) ; persons.Add ( ... ) ; persons.Add ( ... ) ; etc . return persons.Where ( p = > p.FullName.Contains ( `` ... | search object list by computed property |
C# | How can you make a string that is formatted from a value from left to right ? The above returns as 00-00-0123 I would like it to be 12-30-0000Any idea to achieve this ? | string.Format ( `` { 0:00-00-0000 } '' , 123 ) ; | Apply string format form left to right |
C# | I was wondering if this technique has a name - changing state methods to return this , to be able to write them in the linq way method ( ) .method ( ) .method ( ) . | class Program { static void Main ( string [ ] args ) { Test t = new Test ( ) ; t.Add ( 1 ) .Write ( ) .Add ( 2 ) .Write ( ) .Add ( 3 ) .Write ( ) .Add ( 4 ) .Write ( ) .Subtract ( 2 ) .Write ( ) ; } } internal class Test { private int i = 0 ; public Test Add ( int j ) { i += j ; return this ; } public Test Subtract ( i... | C # - How is this technique called ? |
C# | I ran into a nasty bug recently and the simplified code looks like below : ... The value of x after the Increment call is 1 ! This was an easy fix once I found out what was happening . I assigned the return value to a temporary variable and then updated x. I was wondering what explains this issue . Is it something in t... | int x = 0 ; x += Increment ( ref x ) ; private int Increment ( ref int parameter ) { parameter += 1 ; return 1 ; } | ref Parameter and Assignment in same line |
C# | I came across this code : According to the .NET documentation , GetType ( ) is a method , not a class.My question is that how am I able to use the dot with a method , like this GetType ( ) .Name ? | int myInt = 0 ; textBox1.Text = myInt.GetType ( ) .Name ; | Is GetType ( ) a method or a class ? |
C# | I have to apply a method to an object in C # but I have to do it multiple timesYou get the point ... The thing is I know there is a way to avoid that and just put it like this : But I do n't remember if that 's correct in C # , I saw it in another programming language although I do n't remember if that is the correct w... | stud1.setGrade ( 90 ) ; stud1.setGrade ( 100 ) ; stud1.setGrade ( 90 ) ; stud1.setGrade ( 50 ) ; stud1.setGrade ( 90 ) .setGrade ( 100 ) .setGrade ( 70 ) ; | How to avoid repeating `` object.method ( ) '' in C # ? |
C# | Is there any simple way to resemble a truth table in code ? It has 2 inputs and 4 outcomes , as shown below : My current code is : | private void myMethod ( bool param1 , bool param2 ) { Func < int , int , bool > myFunc ; if ( param1 ) { if ( param2 ) myFunc = ( x , y ) = > x > = y ; else myFunc = ( x , y ) = > x < = y ; } else { if ( param2 ) myFunc = ( x , y ) = > x < y ; else myFunc = ( x , y ) = > x > y ; } //do more stuff } | Is there a way to simply resemble a truth table ? |
C# | First of all , I was trying to find out if using Interlocked still requires volatile field definition , and that is my real question.But . Being too lazy to analyse generated MSIL I decided to check it in practice.I 'm trying MSDN example for volatile usage when code should break in release build with optimizations on ... | class Example { volatile int val ; void Do ( ) { Task.Run ( ( ) = > { while ( val == 0 ) Console.WriteLine ( `` running '' ) ; } ) ; Thread.Sleep ( 1000 ) ; Interlocked.Increment ( ref val ) ; Console.WriteLine ( `` done . `` ) ; Console.ReadLine ( ) ; } } | volatile , Interlocked : trying to break code |
C# | in .NET , when I add two SqlDecimals , like so : then s3 has precision 2 , whereas both s1 and s2 have precision 1.This seems odd , especially as the documentation states that the return value of the addition operator is `` A new SqlDecimal structure whose Value property contains the sum . '' I.e . according to the doc... | SqlDecimal s1 = new SqlDecimal ( 1 ) ; SqlDecimal s2 = new SqlDecimal ( 1 ) ; SqlDecimal s3 = s1 + s2 ; | Adding two .NET SqlDecimals increases precision ? |
C# | I work with a SaaS product that has a somewhat large user base . Up until now our approach to isolating customer data has been to have customer specific databases . This has worked great with Entity Framework 6 as all we need to do is pass a customer specific connection string to DbContext and everything works perfectl... | public class CustomDbContext : DbContext public CustomDbContext ( IConnectionStringProvider provider ) : base ( provider.ConnectionString ) { } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Configurations.Add ( new SomeEntityMap ( ) ) ; modelBuilder.Configurations.Add ( new Some... | Entity Framework 's model caching makes it useless with large amounts of database schemas |
C# | I have a foolish doubt.Generally `` System.Object '' implements `` Equals '' . When I implements IEquatable interface i can give custom definition ( I believe so ) to my `` Equals '' . so the professor class implementation is equal to since there are different definitions of System.Equals , and IEquatable 's Equals , W... | class Professor : System.Object , IEquatable class Professor : IEquatable < Professor > { public string Name { get ; set ; } public bool Equals ( Professor cust ) { if ( cust == null ) return false ; return cust.Name == this.Name ; } } | Internals of `` equals '' in .NET |
C# | I have a URL scheme like this : and I also have specific controllers : Sometimes the keywords may look an awful lot like controller URLs , or have some kind of `` /url/thingy '' on them . All of the keyword URLs will be stored in a database and return static content . What I 'd love to be able to do , is have the `` ke... | website.com/keywords website.com/controller/action | MVC controllers bubbling back into the router ? |
C# | I 've created a test application that generates a Code 39 barcode . The problem is that when I display the barcode on screen , it either blurs or gets torn . If I use any BitmapScalingMode other than NearestNeighbor , I get the blurred barcode . When I use NearestNeighbor , I get the diagonal slash as shown below . The... | < Border BorderBrush= '' Black '' BorderThickness= '' 1 '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Top '' Margin= '' 0,50,0,0 '' > < Image x : Name= '' imgBarcode '' Stretch= '' Fill '' RenderOptions.BitmapScalingMode= '' HighQuality '' RenderOptions.EdgeMode= '' Aliased '' / > < /Border > imgBarcode.So... | Bitmap with Nearest Neighbor Causes Tearing |
C# | Possible Duplicate : Why ca n't I use interface with explicit operator ? When I do this : I get a compiler error like this : 'ImageEditor.Effect.implicit operator ImageEditor.IEffect ( ImageEditor.Effect ) ' : user-defined conversions to or from an interface are not allowed.Why are they not allowed ? Is this not a good... | public struct Effect { public IEffect IEffect { get ; private set ; } public Effect ( IEffect effect ) { this.IEffect = effect ; } public static implicit operator IEffect ( Effect effect ) { return effect.IEffect ; } public static explicit operator Effect ( IEffect effect ) { return new Effect ( effect ) ; } } | Why does n't C # allow types that use composition to have implicit conversions for interfaces ? |
C# | I 'm trying to work out how .NET Code Contracts interact with the lock keyword , using the following example : When I run the Code Contract static analysis tool , it prints a a warning : Ensures unproven : this.o1 ! = nullIf I do any of : change the o2 in the lock to o1 , change the o1 inside the lock block to o2 , add... | public class TestClass { private object o1 = new object ( ) ; private object o2 = new object ( ) ; private void Test ( ) { Contract.Requires ( this.o1 ! = null ) ; Contract.Requires ( this.o2 ! = null ) ; Contract.Ensures ( this.o1 ! = null ) ; lock ( this.o2 ) { this.o1 = new object ( ) ; } } } private void Test ( ) {... | Code Contracts warn of `` ensures unproven '' when locks are involved |
C# | I am trying to stop this warning in IIS and I am reading that I should check this object IsClientConnected before I call TransmitFile ( filename ) . Is this correct or is Another way to correct this ? IIS exception Exception information : Exception type : HttpException Exception message : The remote host closed the con... | if ( context.Response.IsClientConnected ) { context.Response.Clear ( ) ; context.Response.ClearContent ( ) ; context.Response.Cache.SetCacheability ( HttpCacheability.NoCache ) ; context.Response.AddHeader ( `` Expires '' , `` -1 '' ) ; context.Response.ContentType = `` application/pdf '' ; context.Response.TransmitFil... | ASP.net host closed the connection |
C# | I 've been using optional parameters in a limited fashion for some time now with .NET 4 . I 've recently thought about how the optional parameters are implemented and something dawned on me . Take the following example : The only requirement for implementing this is that the largest form of the signature void Go ( stri... | public interface ITest { void Go ( string val = `` Interface '' ) ; } void Main ( ) { IA iface = new A ( ) ; A cls = new A ( ) ; iface.Go ( ) ; cls.Go ( ) ; } interface IA { void Go ( string val = `` Interface '' ) ; } class A : IA { public void Go ( string val = `` Class '' ) { val.Dump ( ) ; } } InterfaceClass | Consistency with Optional Parameter Values |
C# | I would like to know in C # or VB.NET if at any time I could send all the output that is written in the debug console of my IDE , to the clipboard.Example Pseudo-Code in vb.net : I would like to copy all the lines of the debug console , including the messages that were written at the moment of execution , just ALL : Wi... | For x as integer = 0 to integer.maxvalue debug.writeline ( `` test console line `` & x ) nextClipboard.SetText ( Debug.Output ) | Send the entire debug console output to clipboard ? |
C# | I 've created the .NET Core 2.1 web application . After , this app was integrated with Azure Active Directory ( Microsoft.AspNetCore.Authentication.AzureAD ) . There are a couple of tenants inside my active directory and in order to authenticate the user there is a need to provide AD tenant id , AD application client i... | public class Startup { // Generated code public void ConfigureServices ( IServiceCollection services ) { services.AddAuthentication ( AzureADDefaults.AuthenticationScheme ) .AddAzureAD ( options = > Configuration.Bind ( `` AzureAd '' , options ) ) ; services.Configure < OpenIdConnectOptions > ( AzureADDefaults.OpenIdSc... | How to authenticate users in Azure Active Directory with dynamic tenants inside single instance of .NET Core web application ? |
C# | Here is a simple test application ( in F # , but I checked and the same problem occurs in C # ) : When running this in VS 11 preview ( no matter which .NET version ) , the `` clicked '' message appears ~0.5 seconds after clicking . The same happens in C # . When I go to the folder where the project is stored and run th... | let but = new Button ( Content = `` click me '' ) but.Click.Add ( fun e - > printfn `` clicked '' ) [ < STAThread > ] do ( new Application ( ) ) .Run ( new Window ( Content = but ) ) | Why are button clicks slow in VS 11 , and how to fix it ? |
C# | Just found out or are valid codes in C # . I can understand it could be easy for the compiler to differentiate between a variable yield and an iterator yield , but still it adds to the confusion and lessen the readability of the code . Do we know the exact reasons why is it allowed ? | foreach ( int yield in items ) { yield return yield * 2 ; } int yield = 10 ; | A local variable can be named as yield |
C# | Could anyone be so nice and explain me why this code shows Derived.DoWork ( double ) . I can come up with some explanations for this behaviour , however I want someone to clarify this for me . | using System ; public class Base { public virtual void DoWork ( int param ) { Console.WriteLine ( `` Base.DoWork '' ) ; } } public class Derived : Base { public override void DoWork ( int param ) { Console.WriteLine ( `` Derived.DoWork ( int ) '' ) ; } public void DoWork ( double param ) { Console.WriteLine ( `` Derive... | How to explain this behaviour with Overloaded and Overridden Methods ? |
C# | I 'm just wondering if it exists better solution for this . | BitConverter.ToInt32 ( sample_guid.ToByteArray ( ) , 0 ) | What is the best method of getting Int32 from first four bytes of GUID ? |
C# | I have two LINQ expressions that I think I should be able to combine into one.I have a list of referrers , each of which references multiple items , and I 'm trying to determine the most popular items . Each referrer conveys a unique vote score to a referenced item . That is , referrer 1 might give a vote of 0.2 , and ... | class Referrer { public double VoteScore { get ; private set ; } public List < int > Items { get ; private set ; } public Referrer ( double v ) { VoteScore = v ; Items = new List < int > ( ) ; } } var Votes = from r in Referrers from v in r.Items select new { ItemNo = v , Vote = r.VoteScore } ; ItemNo:1 , Vote:0.2ItemN... | Is there a better way to combine these two Linq expressions ? |
C# | I have a situation where I need to assign some objects ' properties inside an object initializer . Some of these objects can be null and I need to access their properties , the problem is that they are too many , and using a if/else thing is not good.ExampleThe joined.VisitePdvProduit can be null , and the problem is t... | visits = visitJoins.AsEnumerable ( ) .Select ( joined = > new VisitPDV ( ) { VisiteId = joined.Visite.VisiteId.ToString ( ) , NomPointDeVente = joined.VisitePdvProduit.PointDeVente.NomPointDeVente , } ) ; | Is there a way to Imitate C # 6 Null-Conditional operator in C # 5 |
C# | I am using DateTime.Now.ToString ( `` d '' , new CultureInfo ( `` nl-NL '' ) ) .In a local IIS web application , the output is correct : In a console application , the framework chooses the international/culture-invariant date notation : This is on the same machine , with the exact same code . I have placed a breakpoin... | 22-7-2016 2016-07-22 | DateTime.ToString ( `` d '' , cultureInfo ) output differs between IIS and console app |
C# | I was looking at the source code of Batch method and I have seen this : There is a comment which I did n't quite understand . I have tested this method without using Select and it worked well . But it seems there is something I 'm missing.I ca n't think of any example where this would be necessary , So what 's the actu... | // Select is necessary so bucket contents are streamed tooyield return resultSelector ( bucket.Select ( x = > x ) ) ; private static IEnumerable < TResult > BatchImpl < TSource , TResult > ( this IEnumerable < TSource > source , int size , Func < IEnumerable < TSource > , TResult > resultSelector ) { TSource [ ] bucket... | What is the purpose of using Select ( x = > x ) in a Batch method ? |
C# | I have a method with the following signature : As you might guess , this method returns the value of the cell located at the specified column of the specified row of the specifies table in string format . It turns out that I need this methods almost in all the webpages . Here 's my quetion ( s ) : Should I put this met... | string GetTableCellValue ( DataTable table , string columnName , int rowIndex ) { } | Should I make a method static that will be used across many aspx.cs files |
C# | I have a type Shelter that needs to be covariant , so that an override in another class* can return a Shelter < Cat > where a Shelter < Animal > is expected . Since classes can not be co- or contravariant in C # , I added an interface : However , there is a place where an IShelter ( compile-time type ) is assigned a ne... | public interface IShelter < out AnimalType > { AnimalType Contents { get ; } } IShelter < Cat > shelter = new Shelter ( new Cat ( ) ) ; shelter.Contents = new Cat ( ) ; Error CS1961 Invalid variance : The type parameter 'AnimalType ' must be invariantly valid on 'IShelter < AnimalType > .Contents ' . 'AnimalType ' is c... | How can I add a type invariant setter to a covariant interface ? |
C# | Consider the following code : This creates a pointer to the first character of foo , reassigns it to become mutable , and changes the chars 8 and 9 positions up to ' '.Notice I never actually reassigned foo ; instead , I changed its value by modifying its state , or mutating the string . Therefore , .NET strings are mu... | unsafe { string foo = string.Copy ( `` This ca n't change '' ) ; fixed ( char* ptr = foo ) { char* pFoo = ptr ; pFoo [ 8 ] = pFoo [ 9 ] = ' ' ; } Console.WriteLine ( foo ) ; // `` This can change '' } unsafe { string bar = `` Watch this '' ; fixed ( char* p = bar ) { char* pBar = p ; pBar [ 0 ] = ' C ' ; } string baz =... | Should .NET strings really be considered immutable ? |
C# | I 'm trying to enumerate all namespaces declared in an assembly.Doing something like this feels very inelegant : What is the nice way to do this ? A tree walker will be a bit nicer but asking before as I have a feeling this is already in the symbol API somewhere . | foreach ( var syntaxTree in context.Compilation.SyntaxTrees ) { foreach ( var ns in syntaxTree.GetRoot ( context.CancellationToken ) .DescendantNodes ( ) .OfType < NamespaceDeclarationSyntax > ( ) ) { ... } } | Enumerate namespaces in assembly |
C# | I 've got the following scenario : I 'm looking to insert books , and associated authors if needed . I have the following naive code , which breaks ( pretty much expected ) : What I 'm seeing is that sometimes , the FirstOrDefault is returning null , but the insert is failing due to violation of the unique index on the... | public class Book { [ Key ] public string Isbn { get ; set ; } public string Title { get ; set ; } public int Stock { get ; set ; } public Author Author { get ; set ; } } public class Author { public int AuthorId { get ; set ; } [ Index ( IsUnique = true ) ] [ StringLength ( 50 ) ] public string Name { get ; set ; } pu... | EF6 unique constraint on foreign key |
C# | When I write : it gives `` 12,34 '' , but when I serialize object with double field , it gives `` 12.34 '' It is because XmlSerializer uses some specific format/culture ? What exactly ? I 've looked into Double 's source code but not seen implementation of IXmlSerializable.Thanks . | var d = 12.34D ; d.ToString ( ) ; | What format is used for xml-serialization of numbers in C # ? |
C# | The sample code like this : If the Length property of string will be accessed more than once , is the first snippet code better than the second ? Why ? When we access the length of string in the way of hi.Length , the CLR will count the number of character in hi and return it or just return a 10 cause the Length proper... | string hi = `` HelloWorld '' ; int length = hi.Length ; Console.WriteLine ( length ) ; Console.WriteLine ( length ) ; ... string hi = `` HelloWorld '' ; int length = hi.Length ; Console.WriteLine ( hi.Length ) ; Console.WriteLine ( hi.Length ) ; ... | What will happen when we access the ' Length ' property of string in C # ? |
C# | I am in desperate to find a solution to my problem.Following is the code which generates different task for each item in List < AccountContactView > .Now my problem is when it runs , it only runs for the last item in the array . Any idea about what I am doing wrong ? I do n't want to use Parallel.ForEach becuase it doe... | List < AccountContactViewModel > selectedDataList = DataList.Where ( dataList = > ( bool ) dataList.GetType ( ) .GetProperty ( `` IsChecked '' ) .GetValue ( dataList , new object [ 0 ] ) == true ) .ToList ( ) ; this.IsEnabled = false ; Task validateMarked = Task.Factory.StartNew ( ( ) = > { foreach ( AccountContactView... | Only last task runs ! |
C# | For instance , let 's say I call this method : Is this any more efficient than calling it this way : ? | return bool.TryParse ( s , out _ ) ; return bool.TryParse ( s , out var dummy ) ; | Does using a discard operator `` _ '' in C # optimize the code in any way ? |
C# | I know that await ca n't be used in catch clause.However I have n't really faced a problem related to this , until now ... Basically I have a layer that is responsible for receiving incoming requests , processing them , building messages from them and pass the messages to another layer responsible to send the messages.... | public async Task ProcessRequestAsync ( Request req ) { int statusCode = 0 ; try { await SendMessageAsync ( new Message ( req ) ) ; } catch ( MyCustomException ex ) { statusCode = ex.ErrorCode ; } await SendReponseToClientAsync ( req , statusCode ) ; } public async Task SendMessageAsync ( Message msg ) { try { // Some ... | await forbidden in catch clause . Looking for a work arround |
C# | Suppose I have a DataContext object and access two tables at the same time : Note that I do n't stop using the first query results while making queries to the other table and use the same DataContext object all the time.Is such usage legal ? Should I expect any problems with this approach ? | using ( var context = new DataContext ( connectionString ) ) { foreach ( firstTableEntry in context.GetTable < FirstTable > ( ) ) { switch ( firstTableEntry.Type ) { case RequiresSecondTableAccess : { var secondTable = context.GetTable < SecondTable > ( ) ; var items = secondTable.Where ( item = > item.Id = firstTableE... | Can I access more than one table via the same DataContext object simultaneously ? |
C# | I saw this interesting question which talks about T declaration at the class level and the same letter T ( different meaning ) at the method level.So I did a test.As Eric said , the compiler does warn.But Hey , what happened to type safety ? I assume there is a type safety at the Method level but what about the global ... | static void Main ( string [ ] args ) { var c = new MyClass < int > ( ) ; //T is int c.MyField = 1 ; c.MyProp = 1 ; c.MyMethod ( `` 2 '' ) ; } public class MyClass < T > { public T MyField ; public T MyProp { get ; set ; } public void MyMethod < T > ( T k ) { } } | Generic Type Conflicts ? |
C# | I have seen the code below a lot of times in different threads and different forums . This one in particular I picked up from How does GC and IDispose work in C # ? .My questions are : Is it necessary to create an explicit destructor ? The class inherits from IDisposable and during GC cleanup Dispose ( ) will be eventu... | class MyClass : IDisposable { ... ~MyClass ( ) { this.Dispose ( false ) ; } public void Dispose ( ) { this.Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) { /* dispose managed stuff also */ } /* but dispose unmanaged stuff always */ } } | Please , some clarifications on C # IDisposable |
C# | I 'm very surprised after seeing that I actually have to Instantiate an Interface to use the Word Interoop in C # . The Microsoft.Office.Interop.Word.Application according to what its XML documentation says is an interface : How is it possible , has visual studio confused it with something else ? Or what allows this in... | Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application ( ) ; | Interfaces ca n't be instantiated but is this an exception |
C# | Good day , I am new at ASP.NET and I ca n't figure out why my code does n't work . I have model : And I am trying to create new `` News '' via post form : But when I retrieve data from db I get null pointer exception : , when I called debugger , I figure out that `` news.picture '' value is null . But before db.SaveCha... | using System.ComponentModel.DataAnnotations ; using System.Drawing ; using System.Globalization ; namespace WebApp.Models { public class News { public int NewsId { get ; set ; } public string title { get ; set ; } public string description { get ; set ; } public virtual Picture picture { get ; set ; } public int guid {... | ASP.NET save complex entity model |
C# | i would like to know if it 's possible to do something like this : now i 've got a string like this and an instantiated object of the type car : How would the `` DoSomeMagicalReflectionStuff '' method look like ? And is it even possible to do something like : Thank you ! | class brand { string name ; } class car { string carname ; brand carbrand ; } car carobject = new car ( ) ; string brandNameOfCar = DoSomeMagicalReflectionStuff ( car , `` car.brand.name '' ) ; car carobject = new car ( ) ; string brandNameOfCar = DoSomeMagicalReflectionStuff ( car , `` car.brand.name.ToFormatedString ... | C # : Getting value via reflection |
C# | Possible Duplicate : LINQ : Select parsed int , if string was parseable to int This could be a basic question , but I could n't figure out a work around . I have an array of strings and I tried to parse them with integers . As expected I got Format Exception.How could I skip `` 3a '' and proceed parsing the remaining a... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { string [ ] values = { `` 1 '' , `` 2 '' , `` 3a '' , '' 4 '' } ; List < int > output = new List < int > ( ) ; try { output = values.Select ( i ... | using out type in linq |
C# | I want to use Levenshtein algorithm to search in a list of strings . I want to implement a custom character mapping in order to type latin characters and searching in items in greek.mapping example : So searching using abu in a list with αbuabούαού ( all greek characters ) will result with all items in the list . ( ite... | a = α , άb = βi = ι , ί , ΐ , ϊ ... ( etc ) u = ου , ού | Levenshtein algorithm with custom character mapping |
C# | I run a build system . Datawise the simplified description would be that I have Configurations and each config has 0..n Builds . Now builds produce artifacts and some of these are stored on server . What I am doing is writing kind of a rule , that sums all the bytes produced per configuration builds and checks if these... | private void CalculateExtendedDiskUsage ( IEnumerable < Configuration > allConfigurations ) { var sw = new Stopwatch ( ) ; sw.Start ( ) ; // Lets take only confs that have been updated within last 7 days var items = allConfigurations.AsParallel ( ) .Where ( x = > x.artifact_cleanup_type ! = null & & x.build_cleanup_typ... | Optimizing LINQ routines |
C# | I used CreateThread function to write a class like C # BackgroundWorker in C++.My code : BackgroundWorker.h : BackgroundWorker.cpp : Then I created another class that derived from BackgroundWorker : ListenThread.cpp : But that line gives me the following error : non - standard syntax ; use ' & ' to create a pointer to ... | class BackgroundWorker { private : HANDLE _threadHandle ; unsigned int _threadCallcounter ; DWORD _threadID ; public : BackgroundWorker ( ) ; ~BackgroundWorker ( ) ; virtual DWORD WINAPI Function ( LPVOID vpPram ) ; } # include `` BackgroundWorker.h '' void BackgroundWorker : :DoWork ( ) { this- > _threadHandle = Creat... | Function pointers in C++ |
C# | If I navigate to the following stackoverflow URL http : //stackoverflow.com/questions/15532493 it is automatically appended with the title of the question like so : http : //stackoverflow.com/questions/15532493/mvc-custom-route-gives-404That is , I can type the URL into my browser without the question title and it is a... | routes.MapRoute ( `` UserRoute '' , `` Users/ { *domain } '' , new { controller = `` User '' , action = `` Details '' } , new { action = `` ^Details $ '' } ) ; @ Html.ActionLink ( `` Model.UserName '' , `` Details '' , `` User '' , new { domain = Model.Identity.Replace ( `` \\ '' , `` / '' ) } ) | Stackoverflow style URL ( customising outgoing URL ) |
C# | While doing some performance testing , I 've run into a situation that I can not seem to explain.I have written the following C code : I use gcc to compile it , along with a test driver , into a single binary . I also use gcc to compile it by itself into a shared object which I call from C # via p/invoke . The intent i... | void multi_arr ( int32_t *x , int32_t *y , int32_t *res , int32_t len ) { for ( int32_t i = 0 ; i < len ; ++i ) { res [ i ] = x [ i ] * y [ i ] ; } } | C # calling native code is faster than native calling native |
C# | When MVC runs an ActionMethod it will populate the ModelState dictionary and uses a ModelBinder to build the ActionMethod parameter ( s ) if any . It does this for both GET and POST . Which makes sense.After the ActionMethod successfully has been ran , the view is rendered using the razor supplied , which in my case us... | switch ( inputType ) { case InputType.CheckBox : // ... removed for brevity case InputType.Radio : // ... removed for brevity case InputType.Password : // ... removed for brevity default : string attemptedValue = ( string ) htmlHelper.GetModelStateValue ( fullName , typeof ( string ) ) ; tagBuilder.MergeAttribute ( `` ... | Why does MVC use the Modelstate over a supplied Model on a GET |
C# | Here is my specific scenario with an interface and its implementation : When I access People list I need to make distinction between American , Asian and European and they can share the same interface . Is it good to use additional interfaces ( IAmerican , IAsian , IEuropean ) which all implements IPerson and use that ... | IPerson { string Name ; } American : IPerson { string Name ; } Asian : IPerson { string Name ; } European : IPerson { string Name ; } People = new List < IPerson > ( ) ; // This list can have American , Asian and/or European IAmerican : IPerson { } IAsian : IPerson { } IEuropean : IPerson { } American : IAmerican { str... | Using interface to differentiate implementation |
C# | In C # , younger developers use often `` throw ex '' instead of `` throw '' to throw exception to parent method . Example : '' throw ex '' is a bad practise because the stack trace is truncated below the method that failed . So it 's more difficult to debug code . So the code must be : My question is why compilator aut... | try { // do stuff that can fail } catch ( Exception ex ) { // do stuff throw ex ; } try { // do stuff that can fail } catch ( Exception ex ) { // do stuff throw ; } | Why does the C # compiler authorize `` throw ex '' in catch , and is there a case where `` throw ex '' is useful ? |
C# | What happens to the data that is passed to and from a background worker ? Data is passed from the main thread to the background worker using RunWorkerAsync : This is received in the DoWork event handler in the background thread : After DoWork has processed the data , it returns it using e.Result : This is received in t... | backgroundWorker.RunWorkerAsync ( myData ) ; myData = ( Data ) e.Argument ; e.Result = myData ; myData = ( Data ) e.Result ; | What happens to the data that is passed to and from a background worker ? |
C# | In StringWriter ( mscorlib.dll ) I found a code : I do n't see reason for that ( so is my R # , but it is sometimes wrong ) . ToString ( ) is virtual so the casting does not change behaviour . What kind of optimization is being done here ? | private StringBuilder _sb ; // ( ... ) public override string ToString ( ) { return ( ( object ) this._sb ) .ToString ( ) ; } | Unnecessary casting to object used for calling ToString ( ) in mscorlib |
C# | I have an issue with dapper , I do n't know how to fix this : I have a Poco like this : The field Time is a MySQL 'TIME'.If I load a row with Dapper with a Time field with 1000 ticks for example , and I save this Poco without change anything , reload the same row again , Time field is now at 1001 Ticks.What am I doing ... | public class Test { public long Id { get ; set ; } public TimeSpan ? Time { get ; set ; } } var testobj = Db.Query < Test > ( `` select * from Test where Id = @ id '' , new { id = Id } ) ; Db.Execute ( `` replace into Test values ( @ Id , @ Time ) '' , testObj ) ; { 15:22:24 } Days : 0 Hours : 15 Milliseconds : 0 Minut... | TimeSpan ticks get +1 after save |
C# | I 'm trying to get a good grasp of async/await and I want to clear some of the confusion . Can someone please explain what would be the difference in terms of execution for the following : And : Are they resulting in the same code and why would I write one over the other ? | // version 1public Task Copy ( string source , string destination ) { return Task.Run ( ( ) = > File.Copy ( source , destination ) ) ; } public async Task Test ( ) { await Copy ( `` test '' , `` test2 '' ) ; // do other stuff } // version 2public async Task Copy ( string source , string destination ) { await Task.Run (... | Async/Await Execution Difference |
C# | How I can make something like this in VS properties Window ( collapsible multi properties ) : I tried such code : Where `` Test '' class is : But this gives me only grayed-out name of class | Test z = new Test ( ) ; [ Browsable ( true ) ] public Test _TEST_ { get { return z ; } set { z = value ; } } [ Browsable ( true ) ] public class Test { [ Browsable ( true ) ] public string A { get ; set ; } [ Browsable ( true ) ] public string B { get ; set ; } } | How to create browseable class-properties in .NET / Visual studio |
C# | ( I hope I used 'inverting ' correctly ) I have a collection of nodes ( objects ) and edges ( a list of other objects to which the node refers to ) . The whole graph is represented in a Dictionary < string , List < string > . ( Sidebar : The object in question is not string in reality . The actual type of the object is... | var graph = new Dictionary < string , List < string > > { { `` A '' , new string [ ] { `` C '' , `` D '' } } , { `` B '' , new string [ ] { `` D '' } } , { `` C '' , new string [ ] { `` D '' } } , { `` D '' , new string [ ] { `` B '' } } , //note that C and D refer to each other } ; var graph = new Dictionary < string ... | Inverting a graph |
C# | I have an entity that looks like this : A tiny sample of the data : Ultimately I am trying to get a result that is a list of tiers , within the tiers is a list of classes , and within the class is a distinct grouping of the TankName with the sums of Battles and Victories.Is it possible to do all this in a single LINQ s... | public partial class MemberTank { public int Id { get ; set ; } public int AccountId { get ; set ; } public int Tier { get ; set ; } public string Class { get ; set ; } public string TankName { get ; set ; } public int Battles { get ; set ; } public int Victories { get ; set ; } public System.DateTime LastUpdated { get... | How do I construct a LINQ with multiple GroupBys ? |
C# | So , if I execute the following code ... ... I get 0 , 5 , and 5 , respectively . What I 'd like to get , however is 0 , 1 , and 5 . Is there any way to do a post-increment by n in C # ? Or do I have to write out the += as its own statement ? Just for context , what I 'm actually doing is a bunch of BitConverter operat... | int x = 0 ; Debug.WriteLine ( x++ ) ; Debug.WriteLine ( x += 4 ) ; Debug.WriteLine ( x ) ; | Post-increment x by n ( n ! = 1 ) |
C# | The example below compiles : but this one below failswith Error 1 Can not implicitly convert type 'int ' to 'byte ' . An explicit conversion exists ( are you missing a cast ? ) Does this mean that for C # += operator provides EXPLICIT conversion ? | public static void Main ( ) { Byte b = 255 ; b += 100 ; } public static void Main ( ) { Byte b = 255 ; b = b + 100 ; } | Does += operator ensures an EXPLICIT conversion or implicit CASTING in C # ? |
C# | Here 's what I want to do : This does not compile , however , giving the error `` Type of conditional expression can not be determined because there is no implicit conversion between 'System.IO.TextWriter ' and 'string ' '' . The above code is a simplification of the following : These two calls to Create are perfectly ... | XmlWriter writer = XmlWriter.Create ( ( string.IsNullOrEmpty ( outfile ) ? Console.Out : outfile ) ) ; XmlWriter writer ; if ( string.IsNullOrEmpty ( outfile ) ) { writer = XmlWriter.Create ( Console.Out ) ; // Constructor takes TextWriter } else { writer = XmlWriter.Create ( outfile ) ; // Constructor takes string } | why ca n't I be compact with my desired C # polymorphism ? |
C# | In Delphi , the private modifier is likely unique : you would think has the C # equivalent of : But in Delphi , the private keyword is more unit friend . In other words , other classes in the same code file can access private members . Transcoding Delphi to C # , it would be the equivalent of the following code working... | Contoso = classprivate procedure DoStuff ( ) ; end ; class Contoso { private void DoStuff ( ) { } } public class Contoso { private void DoStuff ( ) { } } internal class Fabrikam { Contoso _contoso ; //constructor Fabrikam ( ) { _contoso = new Contoso ( ) ; _contoso.DoStuff ( ) ; //i can call a private method of another... | Does C # have the equivalent of Delphi 's private modifier |
C# | I have a table that looks like this : And I need to perform a conditional aggregate that results in a new column . The conditions are as follows : If the value is negative then the aggregation starts and does n't stop until the value is positive . Then nothing until the value is negative again ... The result will look ... | Year Value -- -- -- -- -- -- -- -- - 2013 -0.0016 2014 -0.0001 2015 0.0025 2016 -0.0003 2017 0.0023 2018 0.0002 Year Value AggCol 2013 -0.0016 -0.0016 2014 -0.0001 -0.0017 2015 0.0025 0.0008 2016 -0.0003 -0.0003 2017 0.0023 0.002 2018 0.0002 0.0002 create function dbo.fn ( @ cYear numeric , @ rate float ) returns float... | SQL Server : conditional aggregate ; |
C# | First off hi all , and thanks for the many times searching here has helped me out or taught me something . I 've made a custom HUD for a game I play , and am working on an installer in C # , inspired by another HUD for the same game . It downloads and overwrites all the script files to the existing directory : [ I do n... | C : \Program Files ( x86 ) \Steam\steamapps\me\team fortress 2\tf < requestedExecutionLevel level= '' requireAdministrator '' uiAccess= '' false '' / > | Competitor app installs to same folder as mine , without requiring admin priveleges |
C# | This question is similar to c # internal abstract class , how to hide usage outside but my motiviation is different . Here is the scenarioI started with the following : The above compiles fine . But then I decided that I should extract a base class and tried to write the following : And thus the problem , the protected... | internal class InternalTypeA { ... } public class PublicClass { private readonly InternalTypeA _fieldA ; ... } public abstract class PublicBaseClass { protected readonly InternalTypeA _fieldA ; ... } public abstract class PublicBaseClass { private readonly InternalTypeA _fieldA ; protected object FieldA { get { return ... | How to limit subclassing of public abstact class to types in same assembly and thus allow protected members typed to internal types |
C# | This will be a somewhat abstract question.I am working on a Data Access Layer framework which needs to distinguish between a table , its abstract schema/layout , and concrete table records . I 'm afraid that because of this distinction , there will be much code duplication . I could need some input on ways to avoid thi... | + -- -- -- -- -- -+| Foo |+ -- -- -- -- -- -+| +Id : Guid |+ -- -- -- -- -- -+ // these interfaces only need to be implemented once : interface ISchemaField < T > { string Name { get ; } } interface ITableField < T > { string Name { get ; } int Index { get ; } } interface IRecordField < T > { string Name { get ; } int ... | How do I avoid code duplication when modelling a table , its layout , and its records , all of which share the same basic structure ? |
C# | been struggling with this for a while now.I 'm dipping my toe in the WebAPI world and I have a List that can contains products with the same name but different prices . What I need to do is remove all references to a product is variations in price occur.eg.name = `` Cornflakes '' Price = `` 1.99M '' name = `` Cornflake... | public IEnumerable < Product > GetProductsByCategory ( int Id ) { List < Product > sourceProductList = products.Where ( p = > p.CategoryID == Id ) .ToList ( ) ; List < Product > tempProducts = new List < Product > ( ) ; List < Product > targetProductList = new List < Product > ( ) ; foreach ( var product in sourceProdu... | Remove all items from a List < T > if variations of T occur |
C# | I think most people are aware of the following issue which happens when building in Release mode ( code taken from Threading in C # ) : due to compiler optimizations caching the value of complete and thus preventing the child thread from ever seeing the updated value.However , changing the above code a bit : makes the ... | static void Main ( ) { bool complete = false ; var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! complete ) toggle = ! toggle ; } ) ; t.Start ( ) ; Thread.Sleep ( 1000 ) ; complete = true ; t.Join ( ) ; // Blocks indefinitely } class Wrapper { public bool Complete { get ; set ; } } class Test { Wrapper wra... | Volatile weirdness |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.