text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : 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 . Will that array be stored on stack ? Or the performance advantage of using struct will be lost ? <code> struct MotionVector { int [ ] a ; int b ; }
If an array is used as an element in struct ( C # ) , where is it stored ?
C_sharp : 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 of multiple calls to this action and Insert method but they are called once.UPDATEI am facing similar problem but opposite in functioning problem here : Entity not updating using Code-First approachI think these two have same reason of Change Tracking . But one is adding other is not updating . <code> [ HttpPost ] public ActionResult Add ( Models.ViewModels.Loans.LoanEditorViewModel loanEditorViewModel ) { if ( ! ModelState.IsValid ) return View ( loanEditorViewModel ) ; var loanViewModel = loanEditorViewModel.LoanViewModel ; loanViewModel.LoanProduct = LoanProductService.GetLoanProductById ( loanViewModel.LoanProductId ) ; // < -- do n't want to add to this table in database loanViewModel.Borrower = BorrowerService.GetBorrowerById ( loanViewModel.BorrowerId ) ; // < -- do n't want to add to this table in database Models.Loans.Loan loan = AutoMapper.Mapper.Map < Models.Loans.Loan > ( loanEditorViewModel.LoanViewModel ) ; loanService.AddNewLoan ( loan ) ; return RedirectToAction ( `` Index '' ) ; } public int AddNewLoan ( Models.Loans.Loan loan ) { loan.LoanStatus = Models.Loans.LoanStatus.PENDING ; _LoanService.Insert ( loan ) ; return 0 ; } public virtual void Insert ( TEntity entity ) { if ( entity == null ) throw new ArgumentNullException ( nameof ( entity ) ) ; try { entity.DateCreated = entity.DateUpdated = DateTime.Now ; entity.CreatedBy = entity.UpdatedBy = GetCurrentUser ( ) ; Entities.Add ( entity ) ; context.SaveChanges ( ) ; } catch ( DbUpdateException exception ) { throw new Exception ( GetFullErrorTextAndRollbackEntityChanges ( exception ) , exception ) ; } }
Add ( ) method adding duplicate rows for linked models in Code-First Entity Framework
C_sharp : 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 think that the @ is needed since it does n't need to be a string literal , and it 's not a multi-line string . <code> 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_sharp : Is this OK : It feels like it might be wrong , but I 'm not sure . <code> 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_sharp : 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 ? <code> 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_pattern ) ) var phone_check_pattern = `` ^ ( \+ ? | ( \ ( \+ ? [ 0-9 ] { 1,3 } \ ) ) | ) ( [ 0-9.//- ] |\ ( [ 0-9.//- ] +\ ) ) + ( ( x|X| ( ( e|E ) ( x|X ) ( t|T ) ) ) ( [ 0-9.//- ] |\ ( [ 0-9.//- ] +\ ) ) ) ? $ '' ; alert ( new RegExp ( phone_check_pattern ) .test ( `` test input '' ) )
Errors translating regex from .NET to javascript
C_sharp : 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 ? <code> < ItemsControl ItemsSource= '' { Binding TestForList , Mode=OneWay } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplate > < DataTemplate > < Border Margin= '' 5 '' BorderThickness= '' 1 '' BorderBrush= '' Black '' > < TextBlock FontSize= '' 100 '' Text= '' { Binding } '' / > < /Border > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > public List < string > TestForList { get { return new List < string > { `` A '' , `` B '' , `` C '' } ; } }
Making ItemsControl childs resizeable with a splitter
C_sharp : 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.JustTestingData.JustTestingData ' 'Expression.Blend.SampleData.JustTestingData.JustTestingData ' ( HashCode=12963143 ) . BindingExpression : Path='Items ' DataItem='Expression.Blend.SampleData.JustTestingData.JustTestingData ' ( HashCode=12963143 ) ; target element is 'System.Windows.Controls.ListBox ' ( Name='FeedContent ' ) ; target property is 'ItemsSource ' ( type 'System.Collections.IEnumerable ' ) ..Here is my .cs file : Here is my xaml : What am I doing wrong , that nothing loads from source ? I 'm using blend and visual studio 2013 . <code> 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 OpenReadCompletedEventHandler ( wc_OpenReadCompleted ) ; wc.OpenWriteAsync ( new Uri ( `` http : //www.twojapogoda.pl/wiadomosci.xml '' ) ) ; } public void wc_OpenReadCompleted ( object sender , OpenReadCompletedEventArgs e ) { SyndicationFeed feed ; using ( XmlReader reader = XmlReader.Create ( e.Result ) ) { feed = SyndicationFeed.Load ( reader ) ; FeedContent.ItemsSource = feed.Items ; } } } < phone : PhoneApplicationPage xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' xmlns : shell= '' clr-namespace : Microsoft.Phone.Shell ; assembly=Microsoft.Phone '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : Syndication= '' clr-namespace : System.ServiceModel.Syndication ; assembly=System.ServiceModel.Syndication '' x : Class= '' JustTestIt.MainPage '' mc : Ignorable= '' d '' SupportedOrientations= '' Portrait '' Orientation= '' Portrait '' shell : SystemTray.IsVisible= '' True '' > < phone : PhoneApplicationPage.Resources > < DataTemplate x : Key= '' ItemTemplate '' > < StackPanel > < CheckBox IsChecked= '' { Binding date , Mode=TwoWay } '' / > < TextBlock Text= '' { Binding title } '' / > < /StackPanel > < /DataTemplate > < DataTemplate x : Key= '' ItemTemplate1 '' > < StackPanel > < CheckBox IsChecked= '' { Binding date , Mode=TwoWay } '' / > < TextBlock Text= '' { Binding title } '' / > < /StackPanel > < /DataTemplate > < DataTemplate x : Key= '' ItemTemplate2 '' > < StackPanel Width= '' 381 '' > < TextBlock Text= '' { Binding title } '' FontSize= '' 32 '' Foreground= '' # FFFF8B00 '' Margin= '' 0,0,10,0 '' FontFamily= '' Segoe WP Semibold '' / > < TextBlock Text= '' { Binding date } '' Foreground= '' White '' FontFamily= '' Segoe WP Light '' / > < /StackPanel > < /DataTemplate > < DataTemplate x : Key= '' SyndicationItemTemplate '' > < StackPanel > < TextBlock Text= '' { Binding Title.Text } '' / > < /StackPanel > < /DataTemplate > < DataTemplate x : Key= '' SyndicationItemTemplate1 '' > < StackPanel > < TextBlock Text= '' { Binding Title.Text } '' / > < /StackPanel > < /DataTemplate > < DataTemplate x : Key= '' SyndicationItemTemplate2 '' > < StackPanel > < TextBlock Text= '' { Binding Title.Text } '' / > < /StackPanel > < /DataTemplate > < /phone : PhoneApplicationPage.Resources > < phone : PhoneApplicationPage.FontFamily > < StaticResource ResourceKey= '' PhoneFontFamilyNormal '' / > < /phone : PhoneApplicationPage.FontFamily > < phone : PhoneApplicationPage.FontSize > < StaticResource ResourceKey= '' PhoneFontSizeNormal '' / > < /phone : PhoneApplicationPage.FontSize > < phone : PhoneApplicationPage.Foreground > < StaticResource ResourceKey= '' PhoneForegroundBrush '' / > < /phone : PhoneApplicationPage.Foreground > < Grid x : Name= '' LayoutRoot '' Background= '' Transparent '' DataContext= '' { Binding Source= { StaticResource JustTestingData } } '' > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < phone : Panorama Foreground= '' White '' FontFamily= '' Segoe WP Light '' Background= '' Black '' > < phone : Panorama.Title > < TextBlock Text= '' JustTest it ! `` / > < /phone : Panorama.Title > < phone : PanoramaItem x : Name= '' headers '' CacheMode= '' { x : Null } '' Header= '' '' > < phone : PanoramaItem.RenderTransform > < TranslateTransform/ > < /phone : PanoramaItem.RenderTransform > < Grid Margin= '' 0 '' > < ListBox HorizontalAlignment= '' Left '' ItemTemplate= '' { StaticResource ItemTemplate2 } '' ItemsSource= '' { Binding Collection } '' VerticalAlignment= '' Top '' Width= '' 410 '' / > < /Grid > < /phone : PanoramaItem > < phone : PanoramaItem x : Name= '' articles '' CacheMode= '' { x : Null } '' Header= '' '' d : DataContext= '' { d : DesignData /SampleData/SyndicationFeedSampleData.xaml } '' > < phone : PanoramaItem.RenderTransform > < TranslateTransform/ > < /phone : PanoramaItem.RenderTransform > < Grid > < ListBox x : Name= '' FeedContent '' HorizontalAlignment= '' Left '' ItemTemplate= '' { StaticResource SyndicationItemTemplate2 } '' ItemsSource= '' { Binding Items } '' VerticalAlignment= '' Top '' / > < /Grid > < /phone : PanoramaItem > < /phone : Panorama > < /Grid > < /phone : PhoneApplicationPage >
Windows Phone - SyndicationFeed issue
C_sharp : 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 classes , like so : Or , in an extension class , I could do this : Both of these would enable me to use AssignDel in an instantiated class : But I have a requirement to make AssignDel static . This makes the extension way of doing it useless . It still works in InheritsFoo , but I really want to move this to the base class . If I try , the generics argument ca n't be inferred , and I have to change the usage of the method : Is there a way out here , another way of doing this I have n't thought of ? EDIT : to address the issue in the comments about whether or not the extension method would/should work ... I went to the url referenced by @ Mark M. Turns out that if I write it as such ... That compiles ( do n't know if it will run , though ) . Still , do n't think that qualifies as using a static method , since 'foo ' is still considered an instance ; A null instance , but an instance nonetheless . <code> 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 , Action < T , TVal > action ) where T : Foo { } var foo = new InheritsFoo ( ) ; foo.AssignDel ( x = > x.Property1 , handler ) ; InheritsFoo.AssignDel < InheritsFoo , string > ( x = > x.Property1 , handler ) ; InheritsFoo foo = null ; foo.AssignDel ( x = > x.Property1 , handler ) ;
Better way to define static method
C_sharp : 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 singleton class ? I tried to increment an static variable instancenumber that increment each time I pass the constructor and both programs tell me that the instancenumber is 1 . So it should be ok but I need your advice to be sure.Thank you . best regardsClass Singleton : Program 1 : Program 2 : <code> 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 ( ) ; } public static SingletonClass _I { get { return NTCSession._i ; } } private class NTCSession { static NTCSession ( ) { } internal static readonly SingletonClass _i = new SingletonClass ( ) ; } private static List < WeakReference > instances = new List < WeakReference > ( ) ; # endregion //Singleton initialisation public static string askname { get { return myName ; } } } } using System.Windows.Forms ; using SingletonClassLib ; namespace Singletontest { public partial class Form1 : Form { SingletonClass myclass = SingletonClass._I ; public Form1 ( ) { InitializeComponent ( ) ; string Name = SingletonClass.askname ; MessageBox.Show ( `` Program first : `` +Name ) ; } } } using System.Windows.Forms ; using SingletonClassLib ; namespace Singletontest { public partial class Form1 : Form { SingletonClass myclass = SingletonClass._I ; public Form1 ( ) { InitializeComponent ( ) ; string Name = SingletonClass.askname ; MessageBox.Show ( `` Program second : `` +Name ) ; } } }
c # singleton class working well confirmation
C_sharp : 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 public parameterless constructor in order to use it as parameter 'T ' in the generic type or method A.Create ( ) .Is there a solution for such a problem in C # ? <code> 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_sharp : 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 problem is when i click any button , for example Scene2 Button then fade in animation start , at some milliseconds when black screen appear , if i click on this black screen then another scene is open . It wo n't open scene2 Watch this videohttps : //drive.google.com/file/d/0B1H5fdK2PJAnbm5fWDhlN3dVVncpackage linkhttps : //drive.google.com/file/d/0B1H5fdK2PJAnZ2Y1UEFRMmVFbTAScene Manager script : Scene Fader Script : <code> 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 '' ) ; } } public class Fader : MonoBehaviour { public static Fader instance ; [ SerializeField ] private GameObject canvas ; [ SerializeField ] private Animator anim ; void Awake ( ) { makeSingleton ( ) ; } public void Perform ( string levelname ) { StartCoroutine ( FadeInAnimation ( levelname ) ) ; } void makeSingleton ( ) { if ( instance ! = null ) { Destroy ( gameObject ) ; } else { instance = this ; DontDestroyOnLoad ( gameObject ) ; } } IEnumerator FadeInAnimation ( string level ) { canvas.SetActive ( true ) ; anim.Play ( `` FadeIn '' ) ; yield return new WaitForSeconds ( 1f ) ; Application.LoadLevel ( level ) ; anim.Play ( `` FadeOut '' ) ; yield return new WaitForSeconds ( 2f ) ; canvas.SetActive ( false ) ; } }
Button does n't work correct on scene fading
C_sharp : Using the code above , is there a way to prevent the Func < int > random = ( ) = > 4 ; line from getting stepped into when debugging ? <code> 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 ) { return random ( ) ; }
Preventing lambdas from being stepped into when hosting method is DebuggerHidden
C_sharp : 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 contains the assembly and its dependencies . Some of those dependencies ( e.g . log4net ) are contained in the root directory as well because the default domain has it 's separate log . I want to load the job assembly and its dependencies from the assembly directory if they exist there , and if not i want to load them from the application root directory . Both main appdomain and child domains use the same library with Interfaces similar to Quartz 's IJob interface , so this assembly needs to be loaded from the same file.The reason for this rather odd requirement is that application jobs should have automatic update ability . So a specially designed class would download the job from an API , unload the appdomain the job is on , delete the job assembly with all the dependencies and reload the appdomain and restart the job , without interfering with the other jobs operation . I 've tried using AppdomainSetup to set the Assembly directory before the root directory , however my dependencies get resolved from the root directory every time.So basically i want my dependency to be resolved from the1 . Assembly folder if possible2 . Root directory <code> ( root ) \Library\AssemblyName\ domainSetup.PrivateBinPath = @ '' \\Library\\AssemblyName\\ ''
AppDomain dependency resolving order
C_sharp : 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 which can be demonstrated with the lines below : When this is run it will print ABC then move the cursor back to the start of the line and overwrite it with XYZ . Why does this happen ? <code> 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_sharp : 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 `` capitals last '' seems difficult enough I have spared numbers for the moment . <code> Comparison < string > c = ( string x1 , string x2 ) = > StringComparer.Ordinal.Compare ( x1 , x2 ) ; list.Sort ( c ) ;
Case sensitive sorting with capitals last
C_sharp : 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 new property.EDITThere was a problem while making this code . The intended is to validate all options , they must be necessary , it can not return if just one property meets the condition.Thanks everyone , I will try some of the suggested approaches on the comments and I 'll post the results afterUPDATEI have come with a short version for now and more readable based on everyones comments until I can try every approach . Edited to combine all expressions as per @ Alexander Powolozki answer . <code> 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 ValidatedStandardOperationSheet { get ; set ; } public bool ValidatedOperationMethod { get ; set ; } public bool IsComponentsRequired { get ; set ; } public bool IsGeometriesRequired { get ; set ; } public bool IsPokayokesRequired { get ; set ; } public bool IsTechnicalFileRequired { get ; set ; } public bool IsStandardOperationSheetRequired { get ; set ; } public bool IsOperationMethodRequired { get ; set ; } public bool IsProductionReadyToStart ( ) { if ( IsComponentsRequired ) { return ValidatedComponents ; } if ( IsComponentsRequired & & IsGeometriesRequired ) { return ValidatedComponents & & ValidatedGeometries ; } if ( IsComponentsRequired & & IsGeometriesRequired & & IsPokayokesRequired ) { return ValidatedComponents & & ValidatedGeometries & & ValidatedPokayokes ; } if ( IsComponentsRequired & & IsGeometriesRequired & & IsPokayokesRequired & & IsTechnicalFileRequired ) { return ValidatedComponents & & ValidatedGeometries & & ValidatedPokayokes & & ValidatedTechnicalFile ; } if ( IsComponentsRequired & & IsGeometriesRequired & & IsPokayokesRequired & & IsTechnicalFileRequired & & ValidatedStandardOperationSheet ) { return ValidatedComponents & & ValidatedGeometries & & ValidatedPokayokes & & ValidatedTechnicalFile & & ValidatedStandardOperationSheet ; } if ( IsComponentsRequired & & IsGeometriesRequired & & IsPokayokesRequired & & IsTechnicalFileRequired & & IsStandardOperationSheetRequired & & IsOperationMethodRequired ) { return ValidatedComponents & & ValidatedGeometries & & ValidatedPokayokes & & ValidatedTechnicalFile & & ValidatedStandardOperationSheet & & ValidatedOperationMethod ; } return false ; } } public bool IsProductionReadyToStart ( ) { bool isValid = true ; isValid & = ! IsComponentsRequired || ValidatedComponents ; isValid & = ! IsGeometriesRequired || ValidatedGeometries ; isValid & = ! IsPokayokesRequired || ValidatedComponents ; isValid & = ! IsTechnicalFileRequired || ValidatedTechnicalFile ; isValid & = ! IsStandardOperationSheetRequired || ValidatedStandardOperationSheet ; isValid & = ! IsOperationMethodRequired || ValidatedOperationMethod ; return isValid ; }
C # how to shorten multiple If expressions
C_sharp : 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 delete using context.Customers.DeleteObject ( cust ) and call context.SaveChanges ( ) I get an error : Unable to update the EntitySet 'ViewEntity ' because it has a DefiningQuery and no [ DeleteFunction ] element exists element to support the current operation.I have tried setting On Delete Cascade and None and both generate the same error . EDIT : There 's not much code to show , but here you go : <code> 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 ) == DialogResult.Yes ) { // TODO - Fix this this.ReportSchedDBContext.Customers.DeleteObject ( selectedCust ) ; this.ReportSchedDBContext.SaveChanges ( ) ; } }
Deleting Entity Object with 1 to Many Association to View-Based Entity
C_sharp : 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 . <code> 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 [ AnyRef ] ) } class Dyn ( x : AnyRef ) extends Dynamic { def applyDynamic ( message : String ) ( args : Any* ) = { new Dyn ( x.getClass.getMethod ( message , args.map ( _.asInstanceOf [ AnyRef ] .getClass ) : _* ) . invoke ( x , args.map ( _.asInstanceOf [ AnyRef ] ) : _* ) ) } def typed [ A ] = x.asInstanceOf [ A ] override def toString = `` Dynamic ( `` + x + `` ) '' } class ExpandoObject extends Dynamic { private val fields = mutable.Map.empty [ String , Dyn ] def applyDynamic ( message : String ) ( args : Any* ) : Dynamic = { fields get message match { case Some ( v ) = > v case None = > new Assigner ( fields , message ) .dyn } } } class Assigner ( fields : mutable.Map [ String , Dyn ] , message : String ) { def : = ( value : Any ) : Unit = { fields += ( message - > value.dyn ) } }
Implementing ExpandoObject in Scala
C_sharp : 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 of data . Unfortunately , there are differences in the way it works in .NET than from Java . In Java , the library uses Float.intBitsToFloat ( someInt ) where the value of someInt is 1080001175.Later , this number is multiplied by a value to determine start and end position . In this case , the problem occurs when the index value is 2025.According to my calculator , the result of this calculation should be 7071.99984 . But in Java it is exactly 7072 before it is cast to a long , in which case it is still 7072 . In order for the factor to be exactly 7072 , the value of the float would have to be 3.492345679012346.Is it safe to assume the value of the float is actually 3.492345679012346 instead of 3.4923456 ( the value shown in Eclipse ) ? .NET EquivalentNow , I am searching for a way to get the exact same result in .NET . But so far , I have only been able to read this one file using a hack , and I am not entirely certain the hack will work for any file that is generated by the library in Java.According to intBitsToFloat method in Java VS C # ? , the equivalent functionality is using : This makes the calculation : The result before casting to long is 7071.99977925 , which is shy of the 7072 value that Java yields.What I TriedFrom there , I assumed that there must be some difference in the math between Float.intBitsToFloat ( someInt ) and BitConverter.ToSingle ( BitConverter.GetBytes ( value ) , 0 ) to receive such different results . So , I consulted the javadocs for intBitsToFloat ( int ) to see if I can reproduce the Java results in .NET . I ended up with : As you can see , the result is exactly the same as when using BitConverter , and before casting to a float the number is quite a bit lower ( 3.4923455715179443 ) than the presumed Java value of ( 3.492345679012346 ) that is needed for the result to be exactly 7072.I tried this solution , but the resultant value is exactly the same , 3.49234557.I also tried rounding and truncating , but of course that makes all of the other values that are not very close to the whole number wrong.I was able to hack through this by changing the calculation when the float value is within a certain range of a whole number , but as there could be other places where the calculation is very close to the whole number , this solution probably wo n't work universally.Note that the Convert.ToInt64 function does n't work in most cases either , but it has the effect of rounding in this particular case.QuestionHow can I make a function in .NET that returns exactly the same result as Float.intBitsToFloat ( int ) in Java ? Or , how can I otherwise normalize the differences in float calculation so this result is 7072 ( not 7071 ) given the values 1080001175 and 2025 ? Note : It should work the same as Java for all other possible integer values as well . The above case is just one of potentially many places where the calculation is different in .NET.I am using .NET Framework 4.5.1 and .NET Standard 1.5 and it should produce the same results in both x86 and x64 environments . <code> 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 : 3.49234557 int idx = 2025 ; long result2 = ( long ) ( idx * result ) ; // result2 : 7071 public static float Int32BitsToSingle ( int value ) { if ( value == 0x7f800000 ) { return float.PositiveInfinity ; } else if ( ( uint ) value == 0xff800000 ) { return float.NegativeInfinity ; } else if ( ( value > = 0x7f800001 & & value < = 0x7fffffff ) || ( ( uint ) value > = 0xff800001 & & ( uint ) value < = 0xffffffff ) ) { return float.NaN ; } int bits = value ; int s = ( ( bits > > 31 ) == 0 ) ? 1 : -1 ; int e = ( ( bits > > 23 ) & 0xff ) ; int m = ( e == 0 ) ? ( bits & 0x7fffff ) > > 1 : ( bits & 0x7fffff ) | 0x800000 ; //double r = ( s * m * Math.Pow ( 2 , e - 150 ) ) ; // value of r : 3.4923455715179443 float result = ( float ) ( s * m * Math.Pow ( 2 , e - 150 ) ) ; // value of result : 3.49234557 return result ; } float avg = ( idx * averages [ block ] ) ; avgValue = ( long ) avg ; // yields 7071if ( ( avgValue + 1 ) - avg < 0.0001 ) { avgValue = Convert.ToInt64 ( avg ) ; // yields 7072 }
How do I Mimic Number.intBitsToFloat ( ) in C # ?
C_sharp : 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 <code> < 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_sharp : 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 not say it can be either . Furthermore , the example shows GetNamedDataSlot used at every GetData/SetData site ; even within the same thread.For example ( note that BarSlot slot is not created/assigned on all specific threads that the TLS is accessed ) ; I asks this question in relationship to code structure ; any micro performance gains , if any , are a freebie . Any critical issues or performance degradation with the reuse make it not a viable option . <code> 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.GetData ( BarSlot ) ) ; } }
Is it permissible to cache/reuse Thread.GetNamedSlot between threads ?
C_sharp : 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 <code> 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.getPraesenzzeit ( arravialDates [ i ] , userID ) ; int index = 0 ; }
Convert date into datetime format c #
C_sharp : 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 type , but statically dispatched calls use the one for value types . This is ugly and unlikely , but possible.In the vtable , it stores a `` wrapper '' method that unboxes this , then calls the actual method . This sounds inefficient because all the method 's arguments would have to be copied through two calls.There 's special logic that checks for this in callvirt . Even more inefficient : all callvirts incur a ( slight ) penalty . <code> 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_000f : nopIL_0010 : ldloc.1IL_0011 : callvirt instance void I : :M ( ) IL_0016 : nopIL_0017 : ret
How does C # handle calling an interface method on a struct ?
C_sharp : 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 , longitude ) pair and a maximum ( latitude , longitude ) pair instead of one.If I declare a class for results : and modify the aggregate : the ( current , next ) parameters are assumed to be of type BorderBounds instead of Location.Is there a way to construct such an aggregate ? Would it be best to simply convert this to a foreach ? <code> 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.Latitude : current.Latitude , Longitude = ( next.Longitude < current.Longitude ) ? next.Longitude : current.Longitude } ) ; public class BorderBounds { public double MinLatitude ; public double MinLongitude ; public double MaxLatitude ; public double MaxLongitude ; } var borderBounds = border.Aggregate ( new Location ( ) { Latitude = double.MaxValue , Longitude = double.MaxValue } , ( current , next ) = > new BorderBounds ( ) { ... } ) ;
Is it possible to perform a LINQ aggregate over a collection of one type to a different result type ?
C_sharp : 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 skips elements because the the iterator runs over a changing collection , without throwing an exceptionbug ? are n't iterators required to throw InvalidOperationException if the underlaying collection changes ? So my question is Why does iteration over a changing ControlCollection NOT throw InvalidOperationException ? Addendum : The documentation for IEnumerator says : The enumerator does not have exclusive access to the collection ; therefore , enumerating through a collection is intrinsically not a thread-safe procedure . Even when a collection is synchronized , other threads can still modify the collection , which causes the enumerator to throw an exception . <code> 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 { Text = `` A '' , Top = 10 } ) ; this.Controls.Add ( new TextBox { Text = `` B '' , Top = 30 } ) ; this.Controls.Add ( new TextBox { Text = `` C '' , Top = 50 } ) ; this.Controls.Add ( new TextBox { Text = `` D '' , Top = 70 } ) ; foreach ( Control control in this.Controls ) { control.Dispose ( ) ; }
Why does ControlCollection NOT throw InvalidOperationException ?
C_sharp : 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 # ) , because we do n't have enough reason to arbitrarily modify const values through pointers.Exploring further , I find there 's no equivalent to C++ 's low level const pointers in C # , which will be something like : in C # if it had one.Then p can only read the object pointed to , and can not write to it.And for const objects , C # banned the attempts to retrieve their address.In C++ , any attempt to modify the const is either compile error or Undefined Behavior . In C # , I do n't know whether there is any possibility that we can make use of this.So my question is : Is this behavior really well-defined ? Though I know in C # there 's no concept like UB in C++If so , how should I use it ? Or never use it ? Note : In comment section : casting away const in C++ is not related to this question , because It 's valid only when the pointed to object itself is not const , otherwise it 's UB . Plus , I 'm basically talking about C # and compile time behavior.You can ask me to provide more details if you do n't fully understand the question . I found most of people can not understand this correctly , maybe it 's my fault not making it clear . <code> 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_sharp : 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 to write the whole thing in query syntax : Now , ds is of type System.Linq.Enumerable.WhereSelectEnumerableIterator < Dataset.DeviceData , double > and the call to the percentile function fails.Not sure yet what I 'm missing here ... - there is no praticular reason why I 'd prefer the second syntax , but I 'd like to understand the difference ... Thanks for your help ! <code> 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 ( double.NaN ) orderby device.paramValues [ i ] select device.paramValues [ i ] ) ; double median = percentile ( ds as IOrderedEnumerable < double > , 0.5 ) ;
Linq Query syntax vs . Method Chain : return type
C_sharp : 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 , I am using SQL CLR implementation of the C # RegexMatches function with this ^. { 8 } |. { 12 } $ | . { 4 } regular expression which gives me this : Using the above , I can easily build again a correct UNIQUEIDENTIFIER but I am wondering how the OR operator is evaluated in the regular expression . For example , the following will not work : Is it sure that the first regular expression will first match the start and the end of the string , then the other values and is always returning the matches in this order ( I will have issues if for example , 96C6 is matched after 421F ) . <code> 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_sharp : 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 ( could be more than 20-30 ) . Does each different type of container has to go and grab data from the model or is there a better approach for it ? The second thing I am confused with is , my Model is in a different Library . Do I need to create a copy of the model in my web project and populate my local model from that master model , or should I directly query the Master Model for Concrete Class Properties ? As you can see , my SingleContainer contains BaseProperties , which are local declaration of the properties that are already in the Master Model . I do n't see or understand the point of local Model and I am not sure I am right here or not.Sorry I am new to Design Patterns . Any help will be really appreciated , Thanks <code> 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 = value coming from model } public void SetSides ( ) { //panel.someproperty = //value coming from model , //panel.someotherproperty = //value coming from model , } public void SetArea ( ) { throw new NotImplementedException ( ) ; } public System.Web.UI.WebControls.WebControl GetContainer ( ) { return panel ; } } public class ContainerBuilder { private readonly IContainerBuilder objBuilder ; public Builder ( IContainerBuilder conBuilder ) { objBuilder = conBuilder ; } public void BuildContainer ( ) { objBuilder.SetArea ( ) ; objBuilder.SetSections ( ) ; objBuilder.SetSides ( ) ; } public WebControl GetContainer ( ) { return this.objBuilder.GetContainer ( ) ; } } var conBuilder = new ContainerBuilder ( new SingleContainerBuilder ( ) ) ; conBuilder.BuildContainer ( ) ; var container = conBuilder.GetContainer ( ) ;
Builder Design Pattern : Accessing/Passing model data to/in Concrete classes
C_sharp : 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 . <code> 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 Program { static void Main ( string [ ] args ) { b b = new b ( ) ; a a = ( a ) b ; a.Info ( ) ; b.Info ( ) ; Console.ReadLine ( ) ; } } class a { public void Info ( ) { Console.WriteLine ( `` I 'm a '' ) ; } } class b : a { public void Info ( ) { Console.WriteLine ( `` I 'm b '' ) ; } } }
How to achieve same override experience in C # as in Java ?
C_sharp : 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 : //geeks.ms/blogs/lmblanco/archive/2008/09/02/silverlight-datagrid-crear-una-columna-a-partir-de-varios-valores.aspxIs this example the writer use the DartaGrid in the same way than me . Can anyone explain me why in VS2010 I can use this code and In monodevelop 2.4 or monodevelop 2.8 I ca n't ? <code> < 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/2006 '' mc : Ignorable= '' d '' d : DesignHeight= '' 300 '' d : DesignWidth= '' 400 '' xmlns : my= '' clr-namespace : System.Windows.Controls ; assembly=System.Windows.Controls.Data '' > < Grid x : Name= '' LayoutRoot '' Background= '' White '' > < StackPanel Orientation= '' Vertical '' > < TextBlock x : Name= '' lbl1 '' > lblInfo1 < /TextBlock > < TextBlock x : Name= '' lbl2 '' > lblInfo2 < /TextBlock > < TextBox x : Name= '' txt1 '' > Write here < /TextBox > < Button x : Name= '' btn1 '' Content= '' Send '' Click= '' btn1_Click '' / > < my : DataGrid x : Name= '' grData '' Grid.Row= '' 1 '' Width= '' 500 '' Height= '' 250 '' Margin= '' 10 '' AutoGenerateColumns= '' False '' > < my : DataGrid.Columns > < my : DataGridTextColumn Header= '' Código '' / > < my : DataGridTextColumn Header= '' Lote '' / > < my : DataGridTextColumn Header= '' Ciudad '' / > < my : DataGridTextColumn Header= '' País '' / > < /my : DataGrid.Columns > < /my : DataGrid > < /StackPanel > < /Grid > < /UserControl >
moonlight vs. silverlight : : datagrid incompatibility ?
C_sharp : 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 properties are supported.How can I get around this ? <code> 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 ( `` blah '' ) )
search object list by computed property
C_sharp : 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 ? <code> string.Format ( `` { 0:00-00-0000 } '' , 123 ) ;
Apply string format form left to right
C_sharp : 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 ( ) . <code> 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 ( int j ) { i -= j ; return this ; } public Test Write ( ) { Console.WriteLine ( `` i = { 0 } '' , i.ToString ( ) ) ; return this ; } }
C # - How is this technique called ?
C_sharp : 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 the spec or some aspect of C # that I 'm overlooking . <code> 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_sharp : 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 ? <code> int myInt = 0 ; textBox1.Text = myInt.GetType ( ) .Name ;
Is GetType ( ) a method or a class ?
C_sharp : 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 way of doing it . <code> 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_sharp : 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 : <code> 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_sharp : 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 . And nothing breaks . Code works fine ( in this case - main thread terminates gracefully ) with optimizations on and off.Do I still require volatile keyword on a field when I 'm writing to it from one thread using Interlocked and reading from another thread without lock ? Simple example of code from 1-st question where volatile makes difference ? Why does MSDN example still working when I remove volatile keyword and build in release ? Code snippet to illustrate question 1 . <code> 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_sharp : 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 documentation , addition should not change the precision.Am I missing something here ? Is this intended behaviour ? Cheers , Tilman <code> SqlDecimal s1 = new SqlDecimal ( 1 ) ; SqlDecimal s2 = new SqlDecimal ( 1 ) ; SqlDecimal s3 = s1 + s2 ;
Adding two .NET SqlDecimals increases precision ?
C_sharp : 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 perfectly.For reasons irrelevant to this question , we need to move away from this one database per customer model . From data isolation perspective , having one database schema per customer instead of one database per customer seemed like a good idea . After doing some tests , it seems it is pretty much unusable when we are talking about large numbers of different schemas.Here 's a simplified example on how we currently use DbContext : And here is an example on how we thought it could work : Microsoft has been kind enough to allow a way around default caching of database model . Using the schema name as cache key forces Entity Framework to create a new model for each schema . In theory this works . In practice , not really . I created a test app that makes requests to a service that causes the DbContext to be instantiated . It randomizes the CacheKey from a group of 5000 keys , so basically when the app is first started , pretty much each request causes OnModelCreating ( ) to be called . After a few hundred requests the IIS Worker process had eaten all available memory ( was using around 9 GB ) , CPU usage was close to 100 % and the service pretty much stalled.I 've looked at Entity Framework source codes and was hopeful that using an empty string with model builder 's HasDefaultSchema ( ) would make EF to use the database user 's default schema . We could then cache just one model and have the schema `` defined in connection string '' by setting a default schema to each customer 's database credentials . However , EF throws an exception if the schema is an empty string.So the question is , has anyone stumbled into the same problem and if so , how did you solve it ? If the solution is to just fork Entity Framework , I would appreciate any insight on how extensive the required changes are . <code> 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 SomeOtherEntityMap ( ) ) ; } } public class CustomDbContext : DbContext , IDbModelCacheKeyProvider public CustomDbContext ( IConnectionStringProvider provider ) : base ( provider.ConnectionString ) { CacheKey = provider.Schema ; } public string CacheKey { get ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.HasDefaultSchema ( CacheKey ) ; modelBuilder.Configurations.Add ( new SomeEntityMap ( ) ) ; modelBuilder.Configurations.Add ( new SomeOtherEntityMap ( ) ) ; } }
Entity Framework 's model caching makes it useless with large amounts of database schemas
C_sharp : 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 , Why did not C # report error ? .Because I am not overriding `` Equals '' and even not Hiding `` Equals '' using new keyword . <code> 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_sharp : 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 `` keywords '' controller match first ( it just uses { * } ) , and if the URL is n't found in the database , pop back out to the router , and let the matching continue.I 've got a workaround now which puts the universal matching router at the very end , and doing a 302 redirect to the proper controller , but that is a longer round-trip time and is n't necessary if I can pop back out . <code> website.com/keywords website.com/controller/action
MVC controllers bubbling back into the router ?
C_sharp : 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 diagonal only occurs when I resize the window . ( It stays there if I stop in the right spot . ) The image itself does not change size , but instead moves across the screen as I resize the window.I 've tried using RenderOptions.EdgeMode= '' Aliased '' as well , but it does n't seem to have any effect ... Torn / Blurred / Correct WPF Sample Code : Image generation : Sample generation code : Sample rectangle addition : Load Bitmap taken from another StackOverflow question : <code> < 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.Source = loadBitmap ( c.Generate ( barcodeText.Text ) ) ; imgBarcode.Width = c.GetWidth ( ) ; imgBarcode.Height = c.GetHeight ( ) ; Bitmap bmp = new Bitmap ( width , height ) ; using ( Graphics gfx = Graphics.FromImage ( bmp ) ) using ( SolidBrush black = new SolidBrush ( Color.Black ) ) using ( SolidBrush white = new SolidBrush ( Color.White ) ) { // Start the barcode : addBar ( gfx , black , white , '* ' ) ; foreach ( char c in barcode ) { addCharacter ( gfx , black , white , c ) ; } // End the barcode : addBar ( gfx , black , white , '* ' ) ; } g.FillRectangle ( white , left , top , narrow , height ) ; left += narrow ; [ DllImport ( `` gdi32 '' ) ] static extern int DeleteObject ( IntPtr o ) ; public static BitmapSource loadBitmap ( System.Drawing.Bitmap source ) { IntPtr ip = source.GetHbitmap ( ) ; BitmapSource bs = null ; try { bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap ( ip , IntPtr.Zero , Int32Rect.Empty , System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions ( ) ) ; } finally { DeleteObject ( ip ) ; } return bs ; }
Bitmap with Nearest Neighbor Causes Tearing
C_sharp : 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 practice ? <code> 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_sharp : 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 , adding a second line inside the lock block assigning a new object to o2change lock ( this.o2 ) to if ( this.o2 ! = null ) , remove the lock statement entirely.the warning disappears.However , changing the line inside the lock block to var temp = new object ( ) ; ( thus removing all references to o1 from the method ) still causes the warning : So there are two questions : Why is this warning occurring ? What can be done to prevent it ( bearing in mind this is a toy example and there 's actually stuff happening inside the lock in the real code ) ? <code> 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 ( ) { Contract.Requires ( this.o1 ! = null ) ; Contract.Requires ( this.o2 ! = null ) ; Contract.Ensures ( this.o1 ! = null ) ; lock ( this.o2 ) { var temp = new object ( ) ; } }
Code Contracts warn of `` ensures unproven '' when locks are involved
C_sharp : 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 connection . The error code is 0x800703E3 . at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError ( Int32 result , Boolean ? throwOnDisconnect ) updated Code <code> 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.TransmitFile ( filename ) ; context.Response.Flush ( ) ; context.Response.End ( ) ; } else { context.Response.End ( ) ; } try { context.Response.Clear ( ) ; context.Response.ClearContent ( ) ; context.Response.Cache.SetCacheability ( HttpCacheability.NoCache ) ; context.Response.AddHeader ( `` Expires '' , `` -1 '' ) ; context.Response.ContentType = `` application/pdf '' ; context.Response.TransmitFile ( filename ) ; context.ApplicationInstance.CompleteRequest ( ) //context.Response.Flush ( ) ; //context.Response.End ( ) ; } catch ( HttpException hex ) { }
ASP.net host closed the connection
C_sharp : 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 ( string val ) be implemented , in fact we need not implement the optional parameter because the compiler takes care of that wire-up ( although the option to use optional parameters will not be available when using the concrete class directly ) .With this said , to provide the functionality in both places , and for it to be discover-able in the implementation , one could implement the optional declaration in both interface AND implementation . In fact , the productivity tool ReSharper will pull this optional declaration up to the concrete type automatically when implementing an interface . This seems the logical thing to do . However ... What 's to stop us from using different values in the concrete type and interface ? This set off my alarm bells this morning as if someone goes in to change that value , and forgets to persist it down the inheritance of overrides / interfaces , the behaviour will be completely different depending on how you access the object . This could be very frustrating to debug.Try this LINQpad Script : The output will be : Which brings me to my actual question : Question : What ( if any ? ) way can we safeguard this , without losing the ability to use the optional parameter variant from the concrete class , and so it 's discoverable / readable to the coder ? Has anyone encountered this problem before ? How did you solve it ? Is there any best practices that could help prevent this problem from becoming prevalent in a multi-developer large-scale codebase ? <code> 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_sharp : 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 : WindowsApplication6.vshost.exe ' ( CLR v4.0.30319 : WindowsApplication6.vshost.exe ) : Loaded ' C : \Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . etc ... test console line 1 test console line 2 test console line 3 etc ... I hope that maybe using DTE ( or easier ) it could be done , any ideas ? <code> 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_sharp : 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 id.Is there any way to use all tenants for authentication inside my Active Directory ? This is my appsettings.json file : <code> public class Startup { // Generated code public void ConfigureServices ( IServiceCollection services ) { services.AddAuthentication ( AzureADDefaults.AuthenticationScheme ) .AddAzureAD ( options = > Configuration.Bind ( `` AzureAd '' , options ) ) ; services.Configure < OpenIdConnectOptions > ( AzureADDefaults.OpenIdScheme , options = > { // OnTicketReceived , OnAuthenticationFailed , OnTokenValidated } ) } // Generated code } { `` AzureAd '' : { `` Instance '' : `` https : //login.microsoftonline.com '' , `` Domain '' : `` some-domain.com '' , `` TenantId '' : `` 1a10b000-******* '' , `` ClientId '' : `` 15a0421d-******* '' , `` CallbackPath '' : `` /signin-oidc '' } }
How to authenticate users in Azure Active Directory with dynamic tenants inside single instance of .NET Core web application ?
C_sharp : 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 the .exe outside of VS then the message appears instantly after clicking . Apparently the debugging instrumentation is slowing this particular case down tremendously . Why is this and what can be done about it ? <code> 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_sharp : 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 ? <code> foreach ( int yield in items ) { yield return yield * 2 ; } int yield = 10 ;
A local variable can be named as yield
C_sharp : 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 . <code> 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 ( `` Derived.DoWork ( double ) '' ) ; } public static void Main ( ) { int val = 5 ; Derived d = new Derived ( ) ; d.DoWork ( val ) ; } }
How to explain this behaviour with Overloaded and Overridden Methods ?
C_sharp : I 'm just wondering if it exists better solution for this . <code> BitConverter.ToInt32 ( sample_guid.ToByteArray ( ) , 0 )
What is the best method of getting Int32 from first four bytes of GUID ?
C_sharp : 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 referrer 2 might give a vote of 0.03.A simplified Referrer class : My two Linq expressions are : That gives me a list : Now , I can group , sum , and sort with my second expression : Is it possible to combine these into a single expression ? I realize that I can chain the expressions , that is : But that 's not really any different from what I already have -- it 's just nesting the first expression inside the second . Is there another way that combines the two expressions into one ? <code> 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.2ItemNo:3 , Vote:0.2ItemNo:1 , Vote:0.03 var SortedByScore = from v in Votes group v by v.ItemNo into g let score = g.Sum ( ( v ) = > v.Vote ) orderby score descending select new { ItemNo = g.Key , Score = score } ; var SortedByScore = from v in ( from r in ActivatedReferrers from v in r.Items select new { ItemNo = v , Vote = r.VoteScore } ) group v by v.ItemNo into g let score = g.Sum ( ( v ) = > v.Vote ) orderby score descending select new { ItemNo = g.Key , Score = score } ;
Is there a better way to combine these two Linq expressions ?
C_sharp : 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 that there are like dozens of such assignments ( I just took one to shorten the code ) The C # 6 Null-Conditional operator is the perfect solution for this situation , the problem is that I 'm on C # 5 in this project , is there a way to imitate that ? <code> 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_sharp : 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 breakpoint , checked all input , and even tried running the commands in the immediate window at that point . In every situation , the console application gets it wrong.Can anybody explain what causes the difference ? <code> 22-7-2016 2016-07-22
DateTime.ToString ( `` d '' , cultureInfo ) output differs between IIS and console app
C_sharp : 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 actual purpose of using Select ( x = > x ) here ? Here is the full source code for reference : <code> // 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 = null ; var count = 0 ; foreach ( var item in source ) { if ( bucket == null ) bucket = new TSource [ size ] ; bucket [ count++ ] = item ; // The bucket is fully buffered before it 's yielded if ( count ! = size ) continue ; // Select is necessary so bucket contents are streamed too yield return resultSelector ( bucket.Select ( x = > x ) ) ; bucket = null ; count = 0 ; } // Return the last bucket with all remaining elements if ( bucket ! = null & & count > 0 ) yield return resultSelector ( bucket.Take ( count ) ) ; }
What is the purpose of using Select ( x = > x ) in a Batch method ?
C_sharp : 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 method in all the code files or ? Should I have it as a static method of some class , like Utilities_Class or ? Should I have it as a public NON-STATIC method of some class , like Utilities_Class ? The last 2 choices seem to be better idea . But I do n't know which one to choose eventually . <code> string GetTableCellValue ( DataTable table , string columnName , int rowIndex ) { }
Should I make a method static that will be used across many aspx.cs files
C_sharp : 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 new animal , where we know for sure that the animal being set is going to be a Cat . At first , I thought I could just add a set to the Contents property and do : But adding the setter is not possible ; This makes sense , because otherwise I could pass the catshelter to this function : However , I 'm not going to do that . It would be nice to have some way to mark the setter as invariant so that the UseShelter function would only be able to assign an Animal , and so that this would be enforced at compile-time . The reason I need this is because there is a place in my code that knows it has a Shelter < Cat > , and needs to re-assign the Contents property to a new Cat.The workaround I found so far is to add a jucky runtime type check in an explicit set function ; Juck ! The parameter needs to be of type object , so that this function can be specified in the interface . Is there any way to enforce this at compile-time ? * To clarify , there is a function : public virtual IShelter < Animal > GetAnimalShelter ( ) that is overridden and returns an IShelter < Cat > : A minimal working example including most of the code above follows : <code> 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 covariant . private static void UseShelter ( IShelter < Animal > s ) { s.Contents = new Lion ( ) ; } public void SetContents ( object newContents ) { if ( newContents.GetType ( ) ! = typeof ( AnimalType ) ) { throw new InvalidOperationException ( `` SetContents must be given the correct AnimalType '' ) ; } Contents = ( AnimalType ) newContents ; } public override IShelter < Animal > GetAnimalShelter ( ) { IShelter < Cat > = new Shelter < Cat > ( new Cat ( ) ) ; } class Animal { } class Cat : Animal { } class Lion : Animal { } public interface IShelter < out AnimalType > { AnimalType Contents { get ; } void SetContents ( object newContents ) ; } class Shelter < AnimalType > : IShelter < AnimalType > { public Shelter ( AnimalType animal ) { } public void SetContents ( object newContents ) { if ( newContents.GetType ( ) ! = typeof ( AnimalType ) ) { throw new InvalidOperationException ( `` SetContents must be given the correct AnimalType '' ) ; } Contents = ( AnimalType ) newContents ; } public AnimalType Contents { get ; set ; } } class Usage { public static void Main ( ) { IShelter < Cat > catshelter = new Shelter < Cat > ( new Cat ( ) ) ; catshelter.SetContents ( new Cat ( ) ) ; catshelter.SetContents ( new Lion ( ) ) ; // should be disallowed by the compiler } }
How can I add a type invariant setter to a covariant interface ?
C_sharp : 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 mutable.This works so well , in fact , that the following code : will print `` Catch this '' due to string literal interning.This has plenty of applicable uses , for example this : gets replaced by : This could save potentially huge memory allocation / performance costs if you work in a speed-critical field ( e.g . encodings ) .I guess you could say that this does n't count because it `` uses a hack '' to make pointers mutable , but then again it was the C # language designers who supported assigning a string to a pointer in the first place . ( In fact , this is done all the time internally in String and StringBuilder , so technically you could make your own StringBuilder with this . ) So , should .NET strings really be considered immutable ? <code> 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 = `` Watch this '' ; Console.WriteLine ( baz ) ; // Unrelated , right ? } string GetForInputData ( byte [ ] inputData ) { // allocate a mutable buffer ... char [ ] buffer = new char [ inputData.Length ] ; // fill the buffer with input data // ... and a string to return return new string ( buffer ) ; } string GetForInputData ( byte [ ] inputData ) { // allocate a string to return string result = new string ( '\0 ' , inputData.Length ) ; fixed ( char* ptr = result ) { // fill the result with input data } return result ; // return it }
Should .NET strings really be considered immutable ?
C_sharp : 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 . <code> foreach ( var syntaxTree in context.Compilation.SyntaxTrees ) { foreach ( var ns in syntaxTree.GetRoot ( context.CancellationToken ) .DescendantNodes ( ) .OfType < NamespaceDeclarationSyntax > ( ) ) { ... } }
Enumerate namespaces in assembly
C_sharp : 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 author name . Is there some EF trickery that 'll allow this to happen in a simplistic way ? I guess I could use a stored proc , but would like to do it client side if possible . <code> 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 ; } public ICollection < Book > Books { get ; set ; } } var author = _ctx.Authors.FirstOrDefault ( x = > x.Name == command.Author ) ; if ( author == null ) author = new Author { Name = command.Author } ; var book = new Book { Isbn = command.Id , Title = command.Title , Stock = command.Count , Author = author } ; _ctx.Books.Add ( book ) ; await _ctx.SaveChangesAsync ( ) ;
EF6 unique constraint on foreign key
C_sharp : 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 . <code> var d = 12.34D ; d.ToString ( ) ;
What format is used for xml-serialization of numbers in C # ?
C_sharp : 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 property has been assigned a value of 10 at the time hi is initialized or something else ? How about in Java ? <code> 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_sharp : 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 does n't provide the necessary effect of parallelism to increase the progress bar based on completion of each task . <code> 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 ( AccountContactViewModel viewModel in selectedDataList ) { if ( viewModel ! = null ) { Task validate = Task.Factory.StartNew ( ( ) = > ValidateAccount ( viewModel ) , ( TaskCreationOptions ) TaskContinuationOptions.AttachedToParent ) ; } } } ) ; validateMarked.ContinueWith ( x = > this.IsEnabled = true ) ;
Only last task runs !
C_sharp : For instance , let 's say I call this method : Is this any more efficient than calling it this way : ? <code> 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_sharp : 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.If something goes wrong during the sending of the message , a custom exception is thrown , and caught by the message sending layer . At this point , a failure record for this message should be inserted in DB ( takes some time , so async ) , and the exception should be propagated to the upper layer which is in charge of sending an error response to the client that made the request.Here is some very simplified code for illustration purpose below : Of course the request processing layer knows nothing about the DB , it is just in charge of building a message , passing the message to the message processing layer , and send a response to the client ( positive or negative ) .So I think it makes sense ... If an exception happens , my `` business '' layer want to insert a failure record in DB and rethrow the exception so that the `` request '' processing layer can do what 's necessary ( in this context , send a negative response back to the client ) .Should exceptions not be used this way ? It seems clean to me but the fact that I ca n't do this await in the catch clause makes me think there is maybe a code smell with the design ( even if I the idea of handling the exception in one layer then rethrowing it for the upper layer to do some different handling as well sounds to me like it 's exactly what exceptions are made for ) .Any idea arround this ? Thanks ! <code> 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 async operations done here } catch ( MyCustomException ex ) { await InsertFailureForMessageInDbAsync ( msg , ex.ErrorCode ) ; // CA N'T DO THAT throw ; } }
await forbidden in catch clause . Looking for a work arround
C_sharp : 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 ? <code> 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 = firstTableEntry.SecondId ) ; foreach ( var item in items ) { handleItem ( item ) ; } } default : // not accessing the second table } }
Can I access more than one table via the same DataContext object simultaneously ?
C_sharp : 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 context of the class where T already has been declared.I mean if someone would have asked me , I would guess there should be an error there and not a warning.Why the compiler allows that ? ( I would love to hear a reasonable answer ) <code> 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_sharp : 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 eventually executed.What is the significance of the parameter 'disposing ' in Dispose ( bool disposing ) ? Why is it necessary to differentiate between disposing of managed and unmanaged objects ? <code> 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_sharp : 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 interface to be instantiated ? <code> Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application ( ) ;
Interfaces ca n't be instantiated but is this an exception
C_sharp : 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.SaveChanges ( ) it 100 % not null . Looks like I am doing something stupidly wrong , bcs I ca n't find some1 who faced this problem . Thx . <code> 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 { get ; set ; } } public class Picture { public int PictureId { get ; set ; } public byte [ ] image { get ; set ; } public int width { get ; set ; } public int height { get ; set ; } public int hash { get ; set ; } } } // POST : News/Create // To protect from overposting attacks , please enable the specific properties you want to bind to , for // more details see http : //go.microsoft.com/fwlink/ ? LinkId=317598 . [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult Create ( News news , HttpPostedFileBase uploadImage ) { if ( ModelState.IsValid & & uploadImage ! = null ) { byte [ ] imageData = null ; using ( var binaryReader = new BinaryReader ( uploadImage.InputStream ) ) { imageData = binaryReader.ReadBytes ( uploadImage.ContentLength ) ; } news.picture = new Picture ( ) { hash = 0 , image = imageData , width = 0 , height = 0 } ; db.News.Add ( news ) ; db.SaveChanges ( ) ; return RedirectToAction ( `` Index '' ) ; } return View ( news ) ; }
ASP.NET save complex entity model
C_sharp : 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 ! <code> 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_sharp : 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 array and storing the integers into output using Linq. ? Is this a better approach or a DO N'T DO practice ? Pls shed some light on how to use TryParse in this case <code> 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 = > int.Parse ( i ) ) .ToList < int > ( ) ; } catch ( FormatException ) { foreach ( int i in output ) Console.WriteLine ( i ) ; } foreach ( int i in output ) Console.WriteLine ( i ) ; Console.ReadLine ( ) ; } } }
using out type in linq
C_sharp : 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 . ( item order is not a problem ) How do I apply a mapping in the algorithm ? ( this is where I start ) <code> a = α , άb = βi = ι , ί , ΐ , ϊ ... ( etc ) u = ου , ού
Levenshtein algorithm with custom character mapping
C_sharp : 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 are too much . The code for the routine at the moment is following : This does exactly what I want , but I am thinking if I could make it any faster . Currenly I see : The SQL generated by .ToList ( ) looks very messy . ( Everything that is used in WHERE is covered with an index in DB ) I am testing with 200 configurations , so this adds up to 00:00:18.6326722 . I have a total of ~8k items that need to get processed daily ( so the whole routine takes more than 10 minutes to complete ) . I have been randomly googling around this internet and it seems to me that Entitiy Framework is not very good with parallel processing . Knowing that I still decided to give this async/await approch a try ( First time a tried it , so sorry for any nonsense ) .Basically if I move all the processing out of scope like : And : This , for some reason , drops the execution time for 200 items from 18 - > 13 sec . Anyway , from what I understand , since I am awaiting each .ToListAsync ( ) , it is still processed in sequence , is that correct ? So the `` ca n't process in parallel '' claim starts coming out when I replace the foreach ( var configuration in items ) with Parallel.ForEach ( items , async configuration = > . Doing this change results in : A second operation started on this context before a previous asynchronous operation completed . Use 'await ' to ensure that any asynchronous operations have completed before calling another method on this context . Any instance members are not guaranteed to be thread safe.It was a bit confusing to me at first as I await practically in every place where the compiler allows it , but possibly the data gets seeded to fast . I tried to overcome this by being less greedy and added the new ParallelOptions { MaxDegreeOfParallelism = 4 } to that parallel loop , peasant assumption was that default connection pool size is 100 , all I want to use is 4 , should be plenty . But it still fails . I have also tried to create new DbContexts inside the GetData method , but it still fails . If I remember correctly ( ca n't test now ) , I got Underlying connection failed to openWhat possibilities there are to make this routine go faster ? <code> 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_type ! = null & & x.updated_date > DateTime.UtcNow.AddDays ( -7 ) ) .ToList ( ) ; using ( var ctx = new LocalEntities ( ) ) { Debug.WriteLine ( `` Context : `` + sw.Elapsed ) ; var allBuilds = ctx.Builds ; var ruleResult = new List < Notification > ( ) ; foreach ( var configuration in items ) { // all builds for current configuration var configurationBuilds = allBuilds.Where ( x = > x.configuration_id == configuration.configuration_id ) .OrderByDescending ( z = > z.build_date ) ; Debug.WriteLine ( `` Filter conf builds : `` + sw.Elapsed ) ; // Since I do n't know which builds/artifacts have been cleaned up , calculate it manually if ( configuration.build_cleanup_count ! = null ) { var buildCleanupCount = `` 30 '' ; // default if ( configuration.build_cleanup_type.Equals ( `` ReserveBuildsByDays '' ) ) { var buildLastCleanupDate = DateTime.UtcNow.AddDays ( -int.Parse ( buildCleanupCount ) ) ; configurationBuilds = configurationBuilds.Where ( x = > x.build_date > buildLastCleanupDate ) .OrderByDescending ( z = > z.build_date ) ; } if ( configuration.build_cleanup_type.Equals ( `` ReserveBuildsByCount '' ) ) { var buildLastCleanupCount = int.Parse ( buildCleanupCount ) ; configurationBuilds = configurationBuilds.Take ( buildLastCleanupCount ) .OrderByDescending ( z = > z.build_date ) ; } } if ( configuration.artifact_cleanup_count ! = null ) { // skipped , similar to previous block } Debug.WriteLine ( `` Done cleanup : `` + sw.Elapsed ) ; const int maxDiscAllocationPerConfiguration = 1000000000 ; // 1GB // Sum all disc usage per configuration var confDiscSizePerConfiguration = configurationBuilds .GroupBy ( c = > new { c.configuration_id } ) .Where ( c = > ( c.Sum ( z = > z.artifact_dir_size ) > maxDiscAllocationPerConfiguration ) ) .Select ( groupedBuilds = > new { configurationId = groupedBuilds.FirstOrDefault ( ) .configuration_id , configurationPath = groupedBuilds.FirstOrDefault ( ) .configuration_path , Total = groupedBuilds.Sum ( c = > c.artifact_dir_size ) , Average = groupedBuilds.Average ( c = > c.artifact_dir_size ) } ) .ToList ( ) ; Debug.WriteLine ( `` Done db query : `` + sw.Elapsed ) ; ruleResult.AddRange ( confDiscSizePerConfiguration.Select ( iter = > new Notification { ConfigurationId = iter.configurationId , CreatedDate = DateTime.UtcNow , RuleType = ( int ) RulesEnum.TooMuchDisc , ConfigrationPath = iter.configurationPath } ) ) ; Debug.WriteLine ( `` Finished loop : `` + sw.Elapsed ) ; } // find owners and insert ... } } Context : 00:00:00.0609067// first roundFilter conf builds : 00:00:00.0636291Done cleanup : 00:00:00.0644505Done db query : 00:00:00.3050122Finished loop : 00:00:00.3062711// avg roundFilter conf builds : 00:00:00.0001707Done cleanup : 00:00:00.0006343Done db query : 00:00:00.0760567Finished loop : 00:00:00.0773370 foreach ( var configuration in items ) { var confDiscSizePerConfiguration = await GetData ( configuration , allBuilds ) ; ruleResult.AddRange ( confDiscSizePerConfiguration.Select ( iter = > new Notification { ... skiped } private async Task < List < Tmp > > GetData ( Configuration configuration , IQueryable < Build > allBuilds ) { var configurationBuilds = allBuilds.Where ( x = > x.configuration_id == configuration.configuration_id ) .OrderByDescending ( z = > z.build_date ) ; //..skipped var confDiscSizePerConfiguration = configurationBuilds .GroupBy ( c = > new { c.configuration_id } ) .Where ( c = > ( c.Sum ( z = > z.artifact_dir_size ) > maxDiscAllocationPerConfiguration ) ) .Select ( groupedBuilds = > new Tmp { ConfigurationId = groupedBuilds.FirstOrDefault ( ) .configuration_id , ConfigurationPath = groupedBuilds.FirstOrDefault ( ) .configuration_path , Total = groupedBuilds.Sum ( c = > c.artifact_dir_size ) , Average = groupedBuilds.Average ( c = > c.artifact_dir_size ) } ) .ToListAsync ( ) ; return await confDiscSizePerConfiguration ; }
Optimizing LINQ routines
C_sharp : 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 member <code> 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 = CreateThread ( NULL , 0 , this- > Function , & this- > _threadCallcounter , 0 , & this- > _threadID ) ; // ! ! ! ***This part throws an error*** ! ! ! } class ListenThread : public BackgroundWorker { DWORD WINAPI Function ( LPVOID vpPram ) { //DO somthing ... return 0 ; } } ;
Function pointers in C++
C_sharp : 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 appended automatically.How would I go about achieving the same result in my application ? ( Note : I am aware that the question title does n't affect the page that is rendered ) .I have a controller called Users with an action method called Details . I have the following route defined : As this is an intranet application the user is authenticated against their Windows account . I want to append the domain and user name to the URL.If I generate the URL in the view like so : I get a URL that look like this : Domain/Users/ACME/jsmithHowever , if the user navigates to the URL Domain/Users/ by using the browsers navigation bar it matches the route and the user is taken to the user details page . I would like to append the ACME/jsmith/ onto the URL in this case.The research I have done so far indicates I might have to implement a custom route object by deriving from RouteBase and implementing the GetRouteData and GetVirtualPath methods but I do not know where to start with this ( the msdn documentaiton is very thin ) .So what I would like to know is : Is there a way of achieving this without implementing a custom route ? If not , does anyone know of any good resources to get me started implementing a custom route ? If a custom route implementation is required , how does it get at the information which presumably has to be loaded from the database ? Is it OK to have a service make database calls in a route ( which seems wrong to me ) or can the information be passed to the route by the MVC framework ? <code> 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_sharp : 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 is to measure the performance overhead of calling native code from C # .In both C and C # , I create equal length input arrays of random values and then measure how long it takes multi_arr to run . In both C # and C I use the POSIX clock_gettime ( ) call for timing . I have positioned the timing calls immediately preceding and following the call to multi_arr , so input prep time etc do not impact results . I run 100 iterations and report both the average and the min times.Even though C and C # are executing the exact same function , C # comes out ahead about 50 % of the time , usually by a significant amount . For example , for a len of 1,048,576 , C # 's min is 768,400 ns vs C 's min of 1,344,105 . C # 's avg is 1,018,865 vs C 's 1,852,880 . I put some different numbers into this graph ( mind the log scales ) : These results seem extremely wrong to me , but the artifact is consistent across multiple tests . I 've checked the asm and IL to verify correctness . Bitness is the same . I have no idea what could be impacting performance to this degree . I 've put a minimal reproduction example up here.These tests were all run on Linux ( KDE neon , based off Ubuntu Xenial ) with dotnet-core 2.0.0 and gcc 5.0.4.Has anyone seen this before ? <code> 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_sharp : 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 uses as much HtmlHelper calls as possible . Until now , you might think , 'Yes I know how MVC works ' . Hold on , I 'm getting there.When we use e.g . @ Html.TextFor ( m = > m.Name ) MVC uses the code that can be here to render the tag.The interesting part is at the end of the file where we find : What this means is that the Modelstate is used to get a value over a supplied Model . And this makes sense for a POST because when there are validation errors you want MVC to render the view with the values already supplied by the user . The documentation also states this behavior and there are several posts here on StackOverflow confirming this . But it is stated only for POST , as can be seen on this thread for exampleHowever this code is also used when a view is rendered for a GET ! And this makes no sense at all to me . Consider the following action method : with this simple razor markup : I would expect the view to show the newly generated GUID instead of the Id of the original model . However the view shows the Id passed to the actionmethod on the GET request because the ModelState dictionary contains a key with the name Id.My question is not on how to solve this , because that is fairly easy : rename the ActionMethod parameter to something differentClear the ModelState before returning the ActionResult using Modelstate.Clear ( ) Replace the value in the ModelState dictionary and do n't supply a Model to the view at all.My question is : Why is this proces the same for both GET and POST . Is there any valid use case for using the populated ModelState over the supplied Model on a GET . <code> 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 ( `` value '' , attemptedValue ? ? ( ( useViewData ) ? htmlHelper.EvalString ( fullName , format ) : valueParameter ) , isExplicitValue ) ; break ; } public ActionResult GetCopy ( Guid id ) { var originalModel = this.repository.GetById ( id ) ; var copiedModel = new SomeModel { Id = Guid.NewGuid ( ) , Name = originalModel.Name , } ; return this.View ( copiedModel ) ; } @ Html.TextBoxFor ( m = > m.Id ) @ Html.TextBoxFor ( m = > m.Name )
Why does MVC use the Modelstate over a supplied Model on a GET
C_sharp : 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 to differentiate between the implementing class like : New Interfaces are n't of much use but to segregate the objects . Is this a good approach or should I implement some type property in IPerson to differentiate its implementation ? <code> 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 { string Name ; } Asian : IAsian { string Name ; } European : IEuropean { string Name ; } People = new List < IPerson > ( ) ; People.Add ( new American ( ) ) ; People.Add ( new Asian ( ) ) ; People.Add ( new European ( ) ) ; var americans = People.OfType < IAmerican > ( ) ; // Getting all Americans from People
Using interface to differentiate implementation
C_sharp : 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 authorize this ( or does n't display a warning message ? ) Is there a case which `` throw ex '' is useful ? <code> 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_sharp : 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 the RunWorkerCompleted event handler in the main thread : BackgroundWorker is taking care of passing the data between the threads . I am expecting to pass large amounts of data to and from a background worker so I want to know what the overhead of this transfer is , and if there is a better way of processing a large amount of in-memory objects in a background worker . I would also like to know it is possible to access the data in the background worker from the main thread in a thread-safe manner.For reference , I am using C # , .Net 3.5 and Windows Forms . <code> 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_sharp : 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 ? <code> private StringBuilder _sb ; // ( ... ) public override string ToString ( ) { return ( ( object ) this._sb ) .ToString ( ) ; }
Unnecessary casting to object used for calling ToString ( ) in mscorlib
C_sharp : 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 wrong ? EDIT : How I load my row : How I save it : EDIT 2 : A timespan object before save : and after save : You can see that Ticks 553440000000 and become 553450000000EDIT 3 : I use Hans tip with my Test class like this : and it works , but it 's still odd <code> 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 Minutes : 22 Seconds : 24 Ticks : 553440000000 TotalDays : 0.64055555555555554 TotalHours : 15.373333333333333 TotalMilliseconds : 55344000.0 TotalMinutes : 922.4 TotalSeconds : 55344.0 { 15:22:25 } Days : 0 Hours : 15 Milliseconds : 0 Minutes : 22 Seconds : 25 Ticks : 553450000000 TotalDays : 0.64056712962962958 TotalHours : 15.37361111111111 TotalMilliseconds : 55345000.0 TotalMinutes : 922.41666666666674 TotalSeconds : 55345.0 public class Test { public long Id { get ; set ; } private TimeSpan ? _time ; public TimeSpan ? Time { get { if ( _time.HasValue ) return TimeSpan.FromTicks ( ( long ) Math.Floor ( _time.Value.Ticks / 100000000d ) * 100000000 ) ; return _time ; } set { _time = value ; } } }
TimeSpan ticks get +1 after save
C_sharp : 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 ? <code> // 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 ( ( ) = > File.Copy ( source , destination ) ) ; } public async Task Test ( ) { await Copy ( `` test '' , `` test2 '' ) ; // ... }
Async/Await Execution Difference
C_sharp : 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 <code> 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_sharp : ( 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 of no consequence ) Now , I need to invert the graph , so rather than having a list of objects and all the objects they refer to , I have a list of objects and all the objects that refer to them.I can do this pretty easily with a loop , but I imagine there 's a better way using Linq . Is this the case , and if so , how do I do it ? Just to ensure that we 're clear , let 's pretend that my dataset looks like this : I need to transform it into the moral equivalent of this : Thanks in advance ! <code> 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 , List < string > > { { `` A '' , new string [ ] { } } , { `` B '' , new string [ ] { `` D '' } } , { `` C '' , new string [ ] { `` A '' } } , { `` D '' , new string [ ] { `` A '' , `` C '' , `` B '' } } , } ;
Inverting a graph
C_sharp : 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 statement ? Or is there another way to easily get the result ? ( I know I can easily loop through the DbSet several times to produce the list I want ; I am hoping for a more efficient way of getting the same result with LINQ . ) <code> 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 ; set ; } } Id AccountId Tier Class TankName Battles Victories -- - -- -- -- -- - -- -- -- -- - -- -- -- -- - -- -- -- - -- -- -- -- -- 1 432423 5 Heavy KV 105 58 2 432423 6 Heavy IS 70 39 3 544327 5 Heavy KV 200 102 4 325432 7 Medium KV-13 154 110 5 432423 7 Medium KV-13 191 101
How do I construct a LINQ with multiple GroupBys ?
C_sharp : 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 operations on a buffer , and it 'd be really nice to have each one as a self-sufficient statement where the offset is incremented by the size of the data type being converted to . That way , if the buffer format is later changed , I can just add or remove the one line without having to worry about any of the surrounding code . <code> int x = 0 ; Debug.WriteLine ( x++ ) ; Debug.WriteLine ( x += 4 ) ; Debug.WriteLine ( x ) ;
Post-increment x by n ( n ! = 1 )
C_sharp : 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 ? <code> 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_sharp : 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 valid , and this compiles . Is there a way to make this more compact , like I was trying to do with my inline test ? It does n't make sense to me that what I want does n't work . Mentally thinking through this , it seems like the compiler would evaluate string.IsNullOrEmpty ( outfile ) to determine which case to take : If the condition were true , it would go with Console.Out , and then see that it needs to polymorphically choose the version of XmlWriter.Create that takes a TextWriter.If the condition were false , it would go with outfile , and then see that it needs to polymorphically choose the version of XmlWriter.Create that takes a string.Has programming in ML warped my brain ? <code> 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_sharp : 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 : Even though the method DoStuff is private to Contoso , other classes in the same file can call the method.What i do n't want is to make the method internal : because then other code in the assembly can see or call the DoStuff method ; which i do n't want.Does C # support some sort of unit friend or unit internal access modifier ? <code> 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 class } } class Contoso { internal void DoStuff ( ) ; }
Does C # have the equivalent of Delphi 's private modifier
C_sharp : 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 like this : This udf is as close as I have gotten : I am ok with an answer in c # if that would be easier but prefer SQL . The issue with the function I made is I need to be able to grab the results from the previous row to add to value when the value is positive.I was up all night on here searching for clues and no joy ... EDIT : So think of these as CPI values for the year to be applied to your cellphone bill by your carrier ... They are only going to increase your bill by the CPI , and never decrease it ( if CPI is negative ) ... but they will offset the previous years negative CPI by the current years CPI if the Current year CPI is positive ( or the sum results in a positive ) ... That may or may not help but that is the situation lol . <code> 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 floatas begin declare @ pYear numeric declare @ return float set @ pYear = @ cYear - 1 set @ return = ( select case when Value < 0 and @ rate > 0 then null when Value < 0 then Value + @ rate else @ rate end from Table1 where [ year ] = @ pYear ) return @ returnend
SQL Server : conditional aggregate ;
C_sharp : 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't have any control over which folder to use unfortunately , since I 'm modifying files which Valve installed ] In order to delete folders , add folders , or copy files , I 've had to use an app manifest to increase the user permissions every time the exe is launched : Somehow , the installer I 've been inspired by is installing to the same folder that I am , without forcing a UAC prompt . His app only shows a security warning , but if I uncheck the `` always check '' checkbox , I can run it over and over again without having to verify any special permissions : http : //www.trishtech.com/img_art_a/win7_publisher_not_verified_0.jpg & gt ; '' > Any suggestions on how I can make my app more seamless like his ? I 've contacted the author of the other app , and he says he is also using C # , but does n't know of anything special he 's doing to make this work . EDIT : A few things I know we 're doing differently , just in case they make a difference somehow : I 'm using a file browser to decide where to put my files , so the app can be run from anywhere.He 's just outputting them to the same directory as the exe , requiring the exe to be put in the destination folder . I 'm using ILMerge to bundle SharpZipLib with my app.He 's just leaving the dll in his zip file next to the exe . <code> 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_sharp : 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 member is visible outside the assembly but is of an internal type , so it wo n't compile.The issue at hand is how to I ( or can I ? ) tell the compiler that only public classes in the same assembly as PublicBaseClass may inherit from it and therefore _fieldA will not be expossed outside of the assembly ? Or is there another way to do what I want to do , have a public super class and a set of public base classes that are all in the same assembly and use internal types from that assembly in their common ( `` protected '' ) code ? The only idea I have had so far is the following : But that is UGLY ! <code> 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 _fieldA ; } } ... } public class SubClass1 : PublicBaseClass { private InternalTypeA _fieldA { get { return ( InternalTypeA ) FieldA ; } } } public class SubClass2 : PublicBaseClass { private InternalTypeA _fieldA { get { return ( InternalTypeA ) FieldA ; } } }
How to limit subclassing of public abstact class to types in same assembly and thus allow protected members typed to internal types
C_sharp : 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 this.Note that this diagram could describe any of these : a table schema , a concrete table , or a concrete table record , having a field Id with type Guid.All that 's known in the schema is the field 's name and type.In the concrete ( opened ) table , the field 's `` column index '' is additionally known.With records , all of these things are known , plus the field has a concrete value.Translating this to code , I would get lots of similar types ( in pairs of three ) . I 'll use interfaces to keep the example brief ; what I want to show is the similarity of the types : Now I would like to avoid having to write three very similar implementations for every entity in a concrete data model . What are some possible ways to reduce code duplication ? I 've thought of code generation ( e.g . T4 ) , which would be an OK solution , but I would prefer a `` manually '' coded solution ( if there is one ) with fewer lines of code & more readable code.I 've thought about creating one class per entity which implements the schema , table , and record interface all at the same time ... but that feels messy and like a violation of Separation of Concerns . <code> + -- -- -- -- -- -+| 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 Index { get ; } T Value { get ; set ; } } // these three interfaces are an example for one entity ; there would be// three additional types for each additional entity.interface IFooSchema { ISchemaField < Guid > Id { get ; } IFooTable Open ( IDbConnection dbConnection , string tableName ) ; } interface IFooTable { ITableField < Guid > Id { get ; } ICollection < IFooRecord > ExecuteSomeQuery ( ) ; } interface IFooRecord { IRecordField < Guid > Id { get ; } }
How do I avoid code duplication when modelling a table , its layout , and its records , all of which share the same basic structure ?
C_sharp : 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 = `` Cornflakes '' Price = `` 1.89M '' name = `` Rice Krispies '' Price = `` 2.09M '' name = `` Cornflakes '' Price = `` 2.09M '' No cornflakes should appear in my final list.I 've got the bulk written but it 's removing the products too soon and I 'm unsure where I should be removing them.Any help would be greatly appreciated.Note : other cereals are available <code> 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 sourceProductList ) { bool isInTempList = tempProducts.Any ( x = > x.Name == product.Name ) ; if ( ! isInTempList ) { tempProducts.Add ( product ) ; } else { Product tempProduct = product ; bool isPriceDifferent = tempProducts.Where ( y = > y.Name == tempProduct.Name ) .Any ( y = > y.Price ! = tempProduct.Price ) ; if ( isPriceDifferent ) { tempProducts.RemoveAll ( p = > p.Name == product.Name ) ; // too soon as I may have lots of products with the same name // but need to remove based on product.Name } } } targetProductList.AddRange ( tempProducts ) ; return targetProductList ; }
Remove all items from a List < T > if variations of T occur
C_sharp : 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 problem go away ( i.e . the child thread is able to exit after 1 second ) without the use of volatile , memory fences , or any other mechanism that introduces an implicit fence.How does the added encapsulation of the completion flag influence its visibility between threads ? <code> 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 wrapper = new Wrapper ( ) ; static void Main ( ) { var test = new Test ( ) ; var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! test.wrapper.Complete ) toggle = ! toggle ; } ) ; t.Start ( ) ; Thread.Sleep ( 1000 ) ; test.wrapper.Complete = true ; t.Join ( ) ; // Blocks indefinitely } }
Volatile weirdness