text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Current ASAX code ( simplified ) : QuestionIs it safe to pull routes from the DB at this point ? For example : Additional InformationThis question is born out of a lack of knowledge concerning routing as well as a general unfamiliarity with global.asax . In the past , I 've only used global.asax for extremely simple tasks ; DB feels like I 'm taking it to another level . <code> void Application_Start ( object sender , EventArgs e ) { // Enable routing RegisterRoutes ( RouteTable.Routes ) ; } void RegisterRoutes ( RouteCollection routes ) { routes.Add ( `` ContactUsRoute '' , new Route ( `` contact-us '' , new PageRouteHandler ( `` ~/contactus.aspx '' ) ) ) ; } void RegisterRoutes ( RouteCollection routes ) { routes.Add ( `` ContactUsRoute '' , new Route ( `` contact-us '' , new PageRouteHandler ( `` ~/contactus.aspx '' ) ) ) ; // BusinessLogic.GetPageRoutes ( ) returns a List < Route > var dbRoutes = BusinessLogic.GetPageRoutes ( ) ; foreach ( Route route in dbRoutes ) { routes.Add ( route ) ; } } | Creating routes from DB records |
C_sharp : I 'm using JSON.NET to deserialize a JSON file to a dynamic object in C # .Inside a method , I would like to pass in a string and refer to that specified attribute in the dynamic object.For example : Where File is the dynamic object , and Key is the string that gets passed in . Say I 'd like to pass in the key `` foo '' and a value of `` bar '' , I would do : Update ( `` foo '' , `` bar '' ) ; , however due to the nature of the dynamic object type , this results in As opposed to : Is it possible to do what I 'm asking here with the dynamic object ? <code> public void Update ( string Key , string Value ) { File.Key = Value ; } { `` Key '' : '' bar '' } { `` foo '' : '' bar '' } | Referring to dynamic members of C # 'dynamic ' object |
C_sharp : I am trying to convert a C # Dependency Property that limits the maximum length of text entered into a ComboBox to F # . The program is a MVVM program that uses F # for the model and viewmodel , and C # for the view . the working C # code is this : The F # code is this : The problem I am having is that the XAML error I get is : Default value type does not match type of property MaxLengthWhat am I doing wrong ? <code> public class myComboBoxProperties { public static int GetMaxLength ( DependencyObject obj ) { return ( int ) obj.GetValue ( MaxLengthProperty ) ; } public static void SetMaxLength ( DependencyObject obj , int value ) { obj.SetValue ( MaxLengthProperty , value ) ; } // Using a DependencyProperty as the backing store for MaxLength . This enables animation , styling , binding , etc ... public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached ( `` MaxLength '' , typeof ( int ) , typeof ( myComboBoxProperties ) , new UIPropertyMetadata ( OnMaxLengthChanged ) ) ; private static void OnMaxLengthChanged ( DependencyObject obj , DependencyPropertyChangedEventArgs args ) { if ( obj is ComboBox ) { ComboBox comboBox = ( ComboBox ) obj ; comboBox.Loaded += ( sender , e ) = > { TextBox textBox = comboBox.Template.FindName ( `` PART_EditableTextBox '' , comboBox ) as TextBox ; if ( textBox ! = null ) { textBox.SetValue ( TextBox.MaxLengthProperty , args.NewValue ) ; } } ; } } } type myComboBoxProperties ( ) = static let OnMaxLengthChanged ( myobj1 : DependencyObject , args : DependencyPropertyChangedEventArgs ) = let comboBox = myobj1 : ? > ComboBox comboBox.Loaded.Subscribe ( fun _ - > let textBox : TextBox = comboBox.Template.FindName ( `` PART_EditableTextBox '' , comboBox ) : ? > TextBox match textBox with | null - > ( ) |_ - > textBox.SetValue ( TextBox.MaxLengthProperty , args.NewValue ) ) static let MaxLengthProperty = DependencyProperty.RegisterAttached ( `` MaxLength '' , typeof < int > , typeof < myComboBoxProperties > , new UIPropertyMetadata ( OnMaxLengthChanged ) ) static member GetMaxLength ( myobj : DependencyObject ) = myobj.GetValue ( MaxLengthProperty ) : ? > int static member SetMaxLength ( myobj : DependencyObject , value : int ) = myobj.SetValue ( MaxLengthProperty , value ) | Dependency Property in F # Default Value does not match |
C_sharp : Suppose I do something like Does MyList.OrderBy ( x = > x.prop1 ) return the filtered list , and then does it further filter that list by ThenBy ( x = > x.prop2 ) ? In other words , is it equivalent to ? ? ? Because obviously it 's possible to optimize this by running a sorting algorithm with a comparator : If it does do some sort of optimization and intermediate lists are not returned in the process , then how does it know how to do that ? How do you write a class that optimizes chains of methods on itself ? Makes no sense . <code> var Ordered = MyList.OrderBy ( x = > x.prop1 ) .ThenBy ( x = > x.prop2 ) ; var OrderedByProp1 = MyList.OrderBy ( x = > x.prop1 ) ; var Ordered = OrderedByProp1.OrderBy ( x = > x.prop2 ) ; var Ordered = MyList.Sort ( ( x , y ) = > x.prop1 ! = y.prop1 ? x.prop1 < y.prop1 : ( x.prop2 < y.prop2 ) ) ; | Does LINQ know how to optimize `` queries '' ? |
C_sharp : I have a large array of primitive value-types . The array is in fact one dimentional , but logically represents a 2-dimensional field . As you read from left to right , the values need to become ( the original value of the current cell ) + ( the result calculated in the cell to the left ) . Obviously with the exception of the first element of each row which is just the original value.I already have an implementation which accomplishes this , but is entirely iterative over the entire array and is extremely slow for large ( 1M+ elements ) arrays.Given the following example array , BecomesAnd so forth to the right , up to problematic sizes ( 1024x1024 ) The array needs to be updated ( ideally ) , but another array can be used if necessary . Memory footprint is n't much of an issue here , but performance is critical as these arrays have millions of elements and must be processed hundreds of times per second.The individual cell calculations do not appear to be parallelizable given their dependence on values starting from the left , so GPU acceleration seems impossible . I have investigated PLINQ but requisite for indices makes it very difficult to implement.Is there another way to structure the data to make it faster to process ? If efficient GPU processing is feasible using an innovative teqnique , this would be vastly preferable , as this is currently texture data which is having to be pulled from and pushed back to the video card . <code> 0 0 1 0 02 0 0 0 30 4 1 1 00 1 0 4 1 0 0 1 1 12 2 2 2 50 4 5 6 60 1 1 5 6 | Segmented Aggregation within an Array |
C_sharp : I have this kind of code : Foo is a base class and therefor other classes might inherit from it.I would like the OnBar event to always be fired when Bar ( ) is called even if it 's not called explicitly inside Bar.How can it be done ? <code> public class Foo { public SomeHandler OnBar ; public virtual void Bar ( ) { } } | How to invoke an event automatically when a function is called ? |
C_sharp : I 'm checking the sort parameter and building a bunch of if statements : How do I make this better ? <code> if ( sortDirection == `` ASC '' ) { if ( sortBy == `` Id '' ) return customerList.OrderBy ( x = > x.Id ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` FirstName '' ) return customerList.OrderBy ( x = > x.FirstName ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` City '' ) return customerList.OrderBy ( x = > x.City ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; } else { if ( sortBy == `` Id '' ) return customerList.OrderByDescending ( x = > x.Id ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` FirstName '' ) return customerList.OrderByDescending ( x = > x.FirstName ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` City '' ) return customerList.OrderByDescending ( x = > x.City ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; } | How can I improve this sorting code ? |
C_sharp : We have created a lot of NuGet packages . One of them is a tool , and it contains a special compiler and it is installed like a dotnet tool . The name of the command is `` PolyGen '' .We used a similar mechanism to what Grpc.Tools uses , that means we have defined .targets file inside our NugetPackage . And it works well . But when I update my PolyGen , afterwards I have to update the dotnet tool manually with dotnet tool update command.But I see when the Grpc.Tools is updated , the dotnet tool update is automatically executed . And the Package Manager console wrote the following message : How can we define this automatically executed command , to avoid a manual update ? Thank you guys ! <code> Executing nuget actions took 181,36 ms | Execute an action after my nuget package is installed |
C_sharp : I have the need to construct a LINQ To SQL statement at runtime based on input from a user and I ca n't seem to figure out how to dynamically build the WHERE clause.I have no problem with the following : But what I really need is to make the entire WHERE clause dynamic . This way I can add multiple conditions at runtime like this ( rough idea ) : <code> string Filters = `` < value > FOO < /value > '' ; Where ( `` FormattedMessage.Contains ( @ 0 ) '' , Filters ) foreach ( Filter filter in filterlist ) { whereclause = whereclause + `` & & formattedmessage.contains ( filter ) '' ; } | How dynamic can I make my LINQ To SQL Statements ? |
C_sharp : I have a list of work items . Each work item has a start and an end time.So , basically it looks like this : Now I want to get the total time that was worked . Again , basically this is easy : It 's just the sum.But now it gets difficult : How do I calculcate this sum if I want to extract parallel times ? E.g. , is 6.5 hours , but the sum is 7.5 hours . The fact that two work items map to the time between 10 and 11 o'clock makes the difference.How could I solve this for an arbitrary number of work items that can overlap each other in basically every possible way ( surrounding , start overlaps , end overlaps , including ) ? <code> List < Work > works = new List < Work > ( ) ; works.Add ( new Work ( new DateTime ( 2013 , 4 , 30 , 9 , 0 , 0 ) , new DateTime ( 2013 , 4 , 30 , 11 , 0 , 0 ) ) ; 09:00-11:00 = > 2 hours13:00-17:00 = > 4 hours -- -- 06:00 hours 09:00-11:00 = > 2 hours10:00-11:30 = > 1.5 hours13:00-17:00 = > 4 hours -- -- 06:30 hours | Get breaks from a list of times |
C_sharp : I 'm a bit of a novice with Reflection . I 'm hoping that it 's possible to do what I 'd like it to . I 've been working through ProjectEuler to learn the language , and I have a base class called Problem . Every individual PE problem is a separate class , i.e . Problem16 . To run my calculations , I use the following code : I have completed 50 problems now , and I want to create a loop to run them all . My base class Problem has a method that appends to a text file the problem number , the answer , and the execution time that 's called in each class 's default constructor . I could manually change the function call for all 50 , but as I continue to complete problems , this will end up being a lot of work.I 'd much rather do it programatically . I was hoping for this pseudocode become a reality : <code> using System ; using Euler.Problems ; using Euler.Library ; namespace Euler { static class Program { [ STAThread ] static void Main ( ) { Problem prob = new Problem27 ( ) ; } } } for ( int i = 1 ; i < = 50 ; i++ ) { string statement = `` Problem prob = new Problem '' + i + `` ( ) ; '' ; // Execute statement } | How can I use reflection or alternative to create function calls programatically ? |
C_sharp : I 'm getting a null exception , but the field was initialized as an empty list . So how could it be null ? The error occurs on the second line in this method ( on _hydratedProperties ) : And this is how the field is declared : This is how it 's set : This is the full class ( with the comments and non-relevant parts removed ) : Derived class : <code> protected virtual void NotifyPropertyChanged < T > ( Expression < Func < T > > expression ) { string propertyName = GetPropertyName ( expression ) ; if ( ! this._hydratedProperties.Contains ( propertyName ) ) { this._hydratedProperties.Add ( propertyName ) ; } } public abstract class EntityBase < TSubclass > : INotifyPropertyChanged where TSubclass : class { private List < string > _hydratedProperties = new List < string > ( ) ; public Eta Eta { get { return this._eta ; } set { this._eta = value ; NotifyPropertyChanged ( ( ) = > this.Eta ) ; } } [ DataContract ] public abstract class EntityBase < TSubclass > : INotifyPropertyChanged where TSubclass : class { private List < string > _hydratedProperties = new List < string > ( ) ; public bool IsPropertyHydrated ( string propertyName ) { return this._hydratedProperties.Contains ( propertyName ) ; } public event PropertyChangedEventHandler PropertyChanged ; protected virtual void NotifyPropertyChanged < T > ( Expression < Func < T > > expression ) { string propertyName = GetPropertyName ( expression ) ; if ( ! this._hydratedProperties.Contains ( propertyName ) ) { this._hydratedProperties.Add ( propertyName ) ; } PropertyChangedEventHandler handler = PropertyChanged ; if ( handler ! = null ) { handler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public string GetPropertyName < T > ( Expression < Func < T > > expression ) { MemberExpression memberExpression = ( MemberExpression ) expression.Body ; return memberExpression.Member.Name ; } } [ DataContract ] public class Bin : EntityBase < Bin > { private Eta _eta ; [ DataMember ] public Eta Eta { get { return this._eta ; } set { this._eta = value ; NotifyPropertyChanged ( ( ) = > this.Eta ) ; } } } | How is this field null ? |
C_sharp : According to https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods It is possible to explicitly invoke an interface base implementation with the following syntax.But this does n't seem to be implemented yet.Is there a workaround ( e.g reflection ) to achieve this ? Example code to illustrate the problem <code> base ( IInterfaceType ) .Method ( ) ; interface IA { void M ( ) { Console.WriteLine ( `` IA.M '' ) ; } } interface IB : IA { void IA.M ( ) { Console.WriteLine ( `` IB.M '' ) ; } } interface IC : IA { void IA.M ( ) { Console.WriteLine ( `` IC.M '' ) ; } } class D : IA , IB , IC { public void M ( ) { // base ( IB ) .M ( ) ; Is not yet supported apparently ( ( IB ) this ) .M ( ) ; // Throws stack overflow } } class Program { static void Main ( string [ ] args ) { D d = new D ( ) ; d.M ( ) ; } } | C # 8 base interface 's default method invocation workaround |
C_sharp : Since the release of C # 8.0 , I 've really been enjoying the 'void safety ' with nullable reference types . However , while tweaking a library of mine to support the new feature , I stumbled upon a 'problem ' to which I really could n't find an answer anywhere . I 've looked at Microsoft 's release notes and the .NET source code but no luck.TL ; DR : the question is essentially whether or not an IEnumerator < T > 's Current property should be declared as a nullable reference type.Suppose the following implementation of IEnumerator < T > : And suppose the following code to consume the enumerator : The code , as it is , will generate a warning because , obviously , the return type of WebSocketClientEnumerator < TWebSocketClient > .Current is a nullable reference type.The IEnumerator interface is designed in such a way that one 'should ' call the IEnumerator < T > .MoveNext ( ) method to know beforehand if the enumerator has a next value , thereby accomplishing some kind of void safety but obviously , to the eyes of the compiler this means nothing , calling the MoveNext ( ) method does n't intrinsically guarantee that the enumerator 's Current property is not null.I would like my library to compile without warnings though and the compiler wo n't let me leave this.curCli with a null value in the constructor if it is not declared as a nullable reference type and if it is declared nullable then the 'burden ' of checking for a null reference is transferred to the client of the library . Granted , enumerators are generally consumed trough foreach statements hence it 's mostly handeled by the runtime and it 's probably not that big of a deal . It is true that semantically speaking , it makes sense for an enumerator 's Current property to be null because there might be no data to enumerate , but I really do see a conflict between the IEnumerator < T > interface and the nullable reference type feature . I 'm really wondering if there 's a way to make the compiler happy while still maintaining the functionality . And also , what are the conventions in some other languages featuring some void safety mechanisms ? I realize this is kind of an open-ended question but I still think it 's appropriate for SO . Thanks in advance ! <code> public class WebSocketClientEnumerator < TWebSocketClient > : IEnumerator < TWebSocketClient > where TWebSocketClient : WebSocketClient { private WebSocketRoom < TWebSocketClient > room ; private int curIndex ; private TWebSocketClient ? curCli ; public WebSocketClientEnumerator ( WebSocketRoom < TWebSocketClient > room ) { this.room = room ; curIndex = -1 ; curCli = default ( TWebSocketClient ) ; } public bool MoveNext ( ) { if ( ++curIndex > = room.Count ) { return false ; } else { curCli = room [ curIndex ] ; } return true ; } public void Reset ( ) { curIndex = -1 ; } void IDisposable.Dispose ( ) { } public TWebSocketClient ? Current { get { return curCli ; } } object IEnumerator.Current { get { return Current ; } } } public class WebSocketRoom < TWebSocketClient > : ICollection < TWebSocketClient > where TWebSocketClient : WebSocketClient { // ... public void UseEnumerator ( ) { var e = new WebSocketClientEnumerator < TWebSocketClient > ( this ) ; bool hasNext = e.MoveNext ( ) ; if ( hasNext ) { WebSocketClient c = e.Current ; // < = Warning on this line } } // ... } | .NET Implement IEnumerator with nullable reference types |
C_sharp : C # 8 introduced nullable reference types , which is a very cool feature . Now if you expect to get nullable values you have to write so-called guards : These can be a bit repetitive . What I am wondering is if it is possible to avoid writing this type of code for every variable , but instead have a guard-type static void function that throws exception if value is null or just returns if value is not null . Or is this too hard for compiler to infer ? Especially if it 's external library/package ? <code> object ? value = null ; if ( value is null ) { throw new ArgumentNullException ( ) ; } … | Possibility of external functions as nullable guards ? |
C_sharp : I have a class MyClassof which I want to store several instances in a collection . I will often need to check if an instance with a certain name exists , and if it does , retrieve that instance . Since iterating through the whole collection is not an option ( performance ! ) , I thought of a using a collection of key-value-pairs , e.g . an IDictionary < string , MyClass > .My program will also allow renaming instances of MyClass ( it will not allow renaming if name uniqueness would be violated ) . But if I rename a MyClass , I will also need to delete the old entry from the dictionary and add the new one ( i.e . with the new name ) to keep the data consistent.The problem is that I will have several such dictionaries ( which contain subsets of all MyClass instances ) all over the place , and it will be hard to keep track of them and consistently update all dictionaries after every renaming.Is there a way to keep the key-value pairs consistent automatically ? I think I heard of a data structure that allows this , which exists at least in C++ ( unfortunately , I have no idea how it 's called ) . Basically , it should be a collection where the key is not just a plain string but more like a reference to a string ( to the name property in this case ) , but behaves as if it were a string . Does such a thing exist in C # ? Do you have other ideas how to keep the collections consistent ? My only idea is to have a collection of all dictionaries on the highest level of my program and to make the renaming method update all those dictionaries after the actual renaming process . But there must be a better way ! Why this question is not a duplicate of Best way to change dictionary key : I already know that a dictionary does not allow changing the key . I am instead asking for another data structure that is somehow compatible to key changes ( without losing the performance benefit completely ) , and I am asking for other approaches as well . So my question is much more open to input from any direction , as long as it helps to solve the problem of keeping the data consistent . <code> class MyClass { public string Name { get ; set ; } // is unique among all instances public SomeClass Data { get ; set ; } ... } | collection of key-value pairs where key depends on value |
C_sharp : I want to integrate SimpleModal in My ListView edit action so when the user click edit , the modal popup loaded with data through ajax to edit the form .My simple listview : My Bind Code : From FireBug : <code> < asp : ListView ID= '' lv_familyrelation '' runat= '' server '' ItemPlaceholderID= '' RelationContainer '' > < LayoutTemplate > < fieldset id= '' FieldSet1 '' > < legend > Relations < /legend > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > Code < /div > < div class= '' col-lg-4 '' > Name < /div > < div class= '' col-lg-4 '' > < /div > < /div > < asp : PlaceHolder ID= '' RelationContainer '' runat= '' server '' > < /asp : PlaceHolder > < br / > < br / > < asp : LinkButton ID= '' lbtnInitInsert '' runat= '' server '' CssClass= '' btn btn-primary btn-md white_cr '' > < span class= '' glyphicon glyphicon-plus '' > < /span > < /asp : LinkButton > < /fieldset > < /LayoutTemplate > < ItemTemplate > < fieldset > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > < % # Eval ( `` RELATION_CODE '' ) % > < /div > < div class= '' col-lg-4 '' > < % # Eval ( `` RELATION_NAME '' ) % > < /div > < div class= '' col-lg-4 '' > < asp : LinkButton ID= '' lbtn_edit '' runat= '' server '' CssClass= '' btn btn-primary btn-md white_cr '' > < span class= '' glyphicon glyphicon-pencil '' > < /span > < /asp : LinkButton > < /div > < /div > < /div > < /fieldset > < /ItemTemplate > < /asp : ListView > protected void Page_Load ( object sender , EventArgs e ) { if ( ! IsPostBack ) { lv_familyrelation.DataSource = GetRelation ( ) ; lv_familyrelation.DataBind ( ) ; } } < div > < fieldset id= '' FieldSet1 '' > < legend > Relations < /legend > < br > < a id= '' lv_familyrelation_lbtnInitInsert '' class= '' btn btn-primary btn-md white_cr '' href= '' javascript : __doPostBack ( 'lv_familyrelation $ lbtnInitInsert ' , '' ) '' > < span class= '' glyphicon glyphicon-plus '' > < /span > < /a > < br > < br > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > Code < /div > < div class= '' col-lg-4 '' > Name < /div > < div class= '' col-lg-4 '' > < /div > < /div > < /div > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > 1 < /div > < div class= '' col-lg-4 '' > Mother < /div > < div class= '' col-lg-4 '' > < a id= '' lv_familyrelation_lbtn_edit_0 '' class= '' btn btn-primary btn-md white_cr '' href= '' javascript : __doPostBack ( 'lv_familyrelation $ ctrl0 $ lbtn_edit ' , '' ) '' > < span class= '' glyphicon glyphicon-pencil '' > < /span > < /a > < /div > < /div > < /div > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > 2 < /div > < div class= '' col-lg-4 '' > Father < /div > < div class= '' col-lg-4 '' > < a id= '' lv_familyrelation_lbtn_edit_1 '' class= '' btn btn-primary btn-md white_cr '' href= '' javascript : __doPostBack ( 'lv_familyrelation $ ctrl1 $ lbtn_edit ' , '' ) '' > < span class= '' glyphicon glyphicon-pencil '' > < /span > < /a > < /div > < /div > < /div > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > 3 < /div > < div class= '' col-lg-4 '' > Wife < /div > < div class= '' col-lg-4 '' > < a id= '' lv_familyrelation_lbtn_edit_2 '' class= '' btn btn-primary btn-md white_cr '' href= '' javascript : __doPostBack ( 'lv_familyrelation $ ctrl2 $ lbtn_edit ' , '' ) '' > < span class= '' glyphicon glyphicon-pencil '' > < /span > < /a > < /div > < /div > < /div > < /div > < /div > < /fieldset > < /div > | How to use SimpleModal in listView edit action |
C_sharp : I 'm using the RestSharp library to access a REST API.I want all the API requests to go through the same method , so I can add headers , handle errors and do other stuff in a central place.So I made a method that accepts a generic Func < > and that solves most of my problems , but I do n't know how to handle the case where I do n't have a return type.I call it like this : But I came across a problem , a bunch of API calls do n't have a return type because they do n't return data . So I used Client.Execute ( req ) and I get the error saying the type arguments can not be inferred , I tried to pass , but that failed because it could n't convert the non-generic IRestResponse to the typed one.Any ideas on how to tackle this in a nice way ? <code> private T PerformApiCall < T > ( RestRequest restRequest , Func < RestRequest , IRestResponse < T > > restMethod ) { var response = restMethod.Invoke ( restRequest ) ; //handle errors ... . return response.Data ; } var apples = PerformApiCall ( new RestRequest ( '/api/apples ' ) , req = > Client.Execute < List < Apple > > ( req ) ) ; | C # Generics and using the non-generic version from typed method |
C_sharp : I wrote the code : and I expect to see in ouput : only short namesor only long namesor names that occur first , after sorting in alphabetical order , which in this case coincides with `` only short names '' .But I did not expect to see what the program showed up : Short name at the end of the output . ¿ Why ? I tried to rearrange columns in enum : and again I got a surprise in the output : ¿ Why ? Please , explain to me what 's going on here . <code> enum FlipRotate2dEnum : byte { NO = 0 , None = 0 , R2 = 1 , RotateTwice = 1 , FX = 2 , FlipX = 2 , FY = 3 , FlipY = 3 , D1 = 4 , ReflectDiagonal1 = 4 , D2 = 5 , ReflectDiagonal2 = 5 , RC = 6 , RotateClockwise = 6 , RN = 7 , RotateNonClockwise = 7 } class EnumTest { public static void Main ( ) { for ( byte i = 0 ; i < 8 ; ++i ) { FlipRotate2dEnum v = ( FlipRotate2dEnum ) i ; System.Console.WriteLine ( `` { 0 } { 1 } '' , i , v ) ; } } } 0 NO1 R22 FX3 FY4 D15 D26 RC7 RN 0 None1 RotateTwice2 FlipX3 FlipY4 ReflectDiagonal15 ReflectDiagonal26 RotateClockwise7 RotateNonClockwise 0 None1 RotateTwice2 FlipX3 FlipY4 ReflectDiagonal15 ReflectDiagonal26 RotateClockwise7 RN public enum FlipRotate2dEnum : byte { None = 0 , NO = 0 , RotateTwice = 1 , R2 = 1 , FlipX = 2 , FX = 2 , FlipY = 3 , FY = 3 , ReflectDiagonal1 = 4 , D1 = 4 , ReflectDiagonal2 = 5 , D2 = 5 , RotateClockwise = 6 , RC = 6 , RotateNonClockwise = 7 , RN = 7 } class EnumTest { public static void Main ( ) { for ( byte i = 0 ; i < 8 ; ++i ) { FlipRotate2dEnum v = ( FlipRotate2dEnum ) i ; System.Console.WriteLine ( `` { 0 } { 1 } '' , i , v ) ; } } } 0 NO1 R22 FX3 FY4 D15 D26 RC7 RotateNonClockwise | How to convert primitive type value to enum value , when enum contains elements with the same values ? |
C_sharp : I hope this is a simple question : How can you change 2 connection strings at runtime in the Global.asax under Application_Start ( ) Web.configGlobal.asaxDetailsBefore I start getting questions as to why I 'm doing this or reasons I should n't , please refer to the following post Azure Key Vault Connection Strings and N-Layered Design.Essentially , I 'm trying to use Key Vault with an N-Layered application . The WebAPI defines the connection string via the Web.config . In order to avoid hard-coding connection strings , they will be stored in Key Vault . However , due to the Unit Of Work pattern used , I 'm not sure the best route and I 'm currently trying to figure out the potential solution of injecting or changing the connection string at runtime for the Web API project only . <code> < connectionStrings > < add connectionString= '' DB1 '' value= '' '' / > < add connectionString= '' DB2 '' value= '' '' / > < /connectionStrings > protected void Application_Start ( ) { AreaRegistration.RegisterAllAreas ( ) ; GlobalConfiguration.Configure ( WebApiConfig.Register ) ; FilterConfig.RegisterGlobalFilters ( GlobalFilters.Filters ) ; RouteConfig.RegisterRoutes ( RouteTable.Routes ) ; BundleConfig.RegisterBundles ( BundleTable.Bundles ) ; } | How to Change ConnectionStrings at Runtime for a Web API |
C_sharp : I 'm playing with cqs a little bit and I 'm trying to implement this in a class library ( so there 's no IOC , IServiceProvider , etc ) . Here is some code that I wrote : And this si how I am calling my code : But the problem is that inside the dispatcher , I do n't know why the variable handler can not be casted as IQueryHandler < IQuery < T > , T > . Here is some extra data : PS : I know how to make this work ( with dynamic ) , but I want to understand why THIS code is n't working . <code> public interface IQuery < TResult > { } public interface IQueryHandler < TQuery , TResult > where TQuery : IQuery < TResult > { TResult Handle ( TQuery query ) ; } public class Query : IQuery < bool > { public int Value { get ; set ; } } public class QueryHandler : IQueryHandler < Query , bool > { public bool Handle ( Query query ) { return query.Value > 0 ; } } public class Dispatcher { private readonly Dictionary < Type , object > handlers = new Dictionary < Type , object > ( ) ; public Dispatcher ( ) { handlers.Add ( typeof ( Query ) , new QueryHandler ( ) ) ; } public T Dispatch < T > ( IQuery < T > query ) { IQueryHandler < IQuery < T > , T > queryHandler ; if ( ! this.handlers.TryGetValue ( query.GetType ( ) , out object handler ) || ( ( queryHandler = handler as IQueryHandler < IQuery < T > , T > ) == null ) ) { throw new Exception ( ) ; } return queryHandler.Handle ( query ) ; } } Query query = new Query ( ) ; Dispatcher dispatcher = new Dispatcher ( ) ; var result = dispatcher.Dispatch ( query ) ; | some confusion with generic types in c # |
C_sharp : Consider we have a class with event declared : Despite of `` publicness '' of the event , we can not call FooBarEvent.Invoke from outside.This is overcame by modyfing a class with the following approach : Why accessing public events outside is limited by adding and removing listeners only ? <code> public class FooBar { public event EventHandler FooBarEvent ; } public class FooBar { public event EventHandler FooBarEvent ; public void RaiseFooBarEvent ( object sender , EventArgs eventArguments ) { FooBarEvent.Invoke ( sender , eventArguments ) ; } } | Why public event can not be invoked outside directly ? |
C_sharp : I 'm new to Stack Overflow , but tried to put as much informationI have following class structureI am trying to group list of ItemEntity into MasterEntity . Grouping fileds are Field1 , Field2 and Field3.I have done the grouping so far like belowWith in this group , I want to further split this by actual ItemDate and Duration so it looks like below Basically , I want to split this group in to three in this case.As only Group3 is having Date 15th to 17 , it will be one group . From 17th to 22nd Group1 , Group2 and Group3 are same . so that will become another group.And last only Group1 have 22nd to 24 so it become another groupFinal grouped data to be like <code> public class ItemEntity { public int ItemId { get ; set ; } public int GroupId { get ; set ; } public string GroupName { get ; set ; } public DateTime ItemDate { get ; set ; } public string Field1 { get ; set ; } public string Filed2 { get ; set ; } public string Field3 { get ; set ; } public string Field4 { get ; set ; } public int Duration { get ; set ; } } public class MasterEntity { public ItemEntity Item { get ; set ; } public List < int > ItemList { get ; set ; } public List < int > GroupList { get ; set ; } } var items = new List < ItemEntity > { new ItemEntity { ItemId = 100 , GroupId = 1 , GroupName= `` Group 1 '' , ItemDate = new DateTime ( 2018,10,17 ) , Duration = 7 , Field1 = `` Item Name 1 '' , Filed2 = `` aaa '' , Field3= `` bbb '' , Field4= `` abc '' } , new ItemEntity { ItemId = 150 , GroupId = 2 , GroupName= `` Group 2 '' , ItemDate = new DateTime ( 2018,10,17 ) , Duration = 5 , Field1 = `` Item Name 1 '' , Filed2 = `` aaa '' , Field3= `` bbb '' , Field4= `` efg '' } , new ItemEntity { ItemId = 250 , GroupId = 3 , GroupName= `` Group 3 '' , ItemDate = new DateTime ( 2018,10,15 ) , Duration = 7 , Field1 = `` Item Name 1 '' , Filed2 = `` aaa '' , Field3= `` bbb '' , Field4= `` xyz '' } } ; var group = items.GroupBy ( g = > new { g.Field1 , g.Filed2 , g.Field3 } ) .Select ( s = > new MasterEntity { Item = new ItemEntity { Field1 = s.Key.Field1 , Filed2 = s.Key.Filed2 , Field3 = s.Key.Field3 } , ItemList = s.Select ( g = > g.ItemId ) .ToList ( ) , GroupList = s.Select ( g = > g.GroupId ) .ToList ( ) } ) .ToList ( ) ; G1 { ItemEntity : { ItemDate : 15/10/2018 , Duration : 2 , Field1 : `` Item Name 1 '' , Filed2 : `` aaa '' , Field3 : `` bbb '' , } , ItemList : { 250 } , GroupList : { 3 } } , G2 { ItemEntity : { ItemDate : 17/10/2018 , Duration : 5 , Field1 : `` Item Name 1 '' , Filed2 : `` aaa '' , Field3 : `` bbb '' , } , ItemList : { 100,150,250 } , GroupList : { 1,2,3 } } , G3 { ItemEntity : { ItemDate : 22/10/2018 , Duration : 2 , Field1 : `` Item Name 1 '' , Filed2 : `` aaa '' , Field3 : `` bbb '' , } , ItemList : { 100 } , GroupList : { 1 } } | Complex Linq Grouping |
C_sharp : I want to translate keys used in JSON to different languages.I 'm aware this seems like nonsense from a technical perspective when designing interfaces , APIs and so on . Why not use English only in the first place ? Well , I did n't write this requirement ; ) The easiest way to achieve this is probably an attribute : Then I add this attribute to the class I 'd like to serialize : and call JsonConvert.SerializeObject ( ... ) I do n't have a clue how the used MultiLangConverter should actually look like : All the attempts I tried seemed overly complex . Do I actually need a JsonConverter ? Or is a ContractResolver better suited ? <code> /// < summary > serialization language < /summary > public enum Language { /// < summary > English < /summary > EN , /// < summary > German < /summary > DE // some more ... } /// < summary > An Attribute to add different `` translations '' < /summary > public class TranslatedFieldName : Attribute { public string Name { get ; } public Language Lang { get ; } // actually there might be a dictionary with lang-name pairs later on ; but let 's keep it simple public TranslatedFieldName ( string translatedName , Language lang ) { this.Lang = lang ; this.Name = translatedName ; } } /// < summary > I want to serialize classes of this kind to json in different languages < /summary > public class TranslatableObject { [ TranslatedFieldName ( `` deutscher_schluessel '' , Language.DE ) ] public string english_key ; } public void SerializationMethod ( ) { TranslatableObject to = new TranslatableObject ( ) { english_key = `` foo bar '' } ; string englishJson = JsonConvert.SerializeObject ( to ) ; // == { `` english_key '' : `` foo bar '' } string germanJson = JsonConvert.SerializeObject ( to , new MultiLangConverter ( Language.DE ) ; // == { `` deutscher_schluessel '' : `` foo bar '' } } public class MultiLangConverter : JsonConverter { private readonly Language _lang , public MultiLangConverter ( ) : this ( Language.EN ) { } public MultiLangConverter ( Language lang ) { _lang = lang ; } public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { throw new NotImplementedException ( `` Out of scope for now '' ) ; } public override bool CanRead { get { return false ; } // out of scope for now } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { // what goes here ? } } | Different `` translated '' JsonProperty names |
C_sharp : So , I currently have a Board class that is composed of Pieces . Each Piece has a color and a string that describes the kind of piece . It also has a 2d matrix with bits either set on or off , that allows me to know which pixels to paint with the desired color or not.My question is , which class should have the responsability to draw the pieces on the board ? On one hand , I 'd say the Piece class should do it . But to do it , I 'd have to pass a Board as reference to Piece 's Draw ( ) method and although it 's not terrible I find it kinda awkward . This raises the problem that Piece would have `` to know '' the Board class.On the other hand , I could just have the Piece have aand Board would then have a method of the form : How would you do it ? And why ? I ca n't see a clear winner in any of these approaches.ThankseditI 'm not talking about actually drawing things on screen . What happens is that I 'm implementing a Tetris game ( currently , no GUI ) and I need at every moment to set the Pixels of a Square on different positions on the board as it falls to the ground . The board basically only has an accessor and a mutator for each one of the ( x , y ) points . Let 's now say I want to draw a Square ( a type of Piece ) on the Board . Should the Piece know of the board and its Draw ( ) method make the changes to the Board , or should the Board access Piece 's getter method and do it itself ? <code> Boolean [ , ] IsPixelSet ( int x , int y ) void DrawPieceOnBoard ( ) { for ( int y = 0 ; y < height ; ++y ) { for ( int x = 0 ; x < width ; ++x ) { if ( piece.IsPixelSet ( x , y ) { board.DrawPixelAt ( x , y , piece.GetColor ( ) ) ; } } } } | Which class has the responsibility of setting Piece 's pixels on a Board ( 2d matrix ) ? The Piece or the Board ? |
C_sharp : I am working on a framework that uses some Attribute markup . This will be used in an MVC project and will occur roughly every time I view a specific record in a view ( eg /Details/5 ) I was wondering if there is a better/more efficient way to do this or a good best practices example.At any rate , I have an a couple of attributes e.g : What is the most efficient way/best practice to look for these attributes/Act on their values ? I am currently doing something like this : And in my method where I act on these attributes ( simplified example ! ) : <code> [ Foo ( `` someValueHere '' ) ] String Name { get ; set ; } [ Bar ( `` SomeOtherValue '' ] String Address { get ; set ; } [ System.AttributeUsage ( AttributeTargets.Property ) ] class FooAttribute : Attribute { public string Target { get ; set ; } public FooAttribute ( string target ) { Target = target ; } } public static void DoSomething ( object source ) { //is it faster if I make this a generic function and get the tpe from T ? Type sourceType = source.GetType ( ) ; //get all of the properties marked up with a foo attribute var fooProperties = sourceType .GetProperties ( ) .Where ( p = > p.GetCustomAttributes ( typeof ( FooAttribute ) , true ) .Any ( ) ) .ToList ( ) ; //go through each fooproperty and try to get the value set foreach ( var prop in fooProperties ) { object value = prop.GetValue ( source , null ) ; // do something with the value prop.SetValue ( source , my-modified-value , null ) ; } } | Best way to access attributes |
C_sharp : I 've got a code In .net 3.5 expression evaluates as false , but in 4.0 it evaluates as true . My question is why ? and how can i check all of my old ( .net 3.5 ) code to prevent this behaviour ? <code> byte [ ] bytes = new byte [ ] { 0x80 , 1 , 192 , 33 , 0 } ; if ( bytes [ 0 ] ! = 0x80 || ( ( bytes [ 1 ] & ~1 ) ! = 0 ) || bytes [ 4 ] ! = 0 ) { //signature wrong ( .net 4.0 result ) } else { //signture okay ( .net 3.5 result ) } | Strange difference between .net 3.5 and .net 4.0 |
C_sharp : Is there a way to make the analyzer understand that the variable Bar has a value for the following case ? There is the warning `` Nullable value type may be null . '' for Bar.Value but it obviously ca n't be.I am aware of two ways to avoid the warning . Both have disadvantages : Using Bar.HasValue directly instead of the property GenerateArray . However using GenerateArray improves readability.Using Bar ! .Value instead of Bar.Value . However , if someone changes the code , for instance , by making GenerateArray an auto-property in the future , the warning may become relevant again , but wo n't appear.The problem here slightly differs from this question , where a local variable was used instead of a property . The accepted answer below works ( as soon as C # 9 is released ) for the property but not for the local variable , if I understand it correctly . Hence , the question is not a duplicate . <code> # nullable enable class Foo { bool GenerateArray = > Bar.HasValue ; int ? Bar { get ; set ; } void FooBar ( ) { var data = ( GenerateArray ) ? new int [ Bar.Value ] : null ; } } | How to avoid irrelevant nullable warning ( without explicit suppression ) |
C_sharp : Is there a way that I can track and intercept calls to values in properties that are auto implemented ? I 'd like to have code that looks a bit like this : Ideally the attribute would be able to intercept changes to the property values . Is this possible ? What I do n't want it to have a second piece of code spin over an object later and request the values , but rather the attribute should tack the value as it is being set . <code> [ Tracked ] public int SomeProperty { get ; set ; } | Track calls to auto implemented properties |
C_sharp : I am very new to EWS and Exchange in general , so not really sure what is the best approach.BackgroundI am trying to set configuration information about a room . I was hoping that the EWS API provided me with a Room object that I can add ExtendedProperties on , however , it appears that rooms are just an email address.I then saw that each room had a CalendarFolder associated with it , so I am now trying to set the room configuration in the CalendarFolder , which is what the original question below refers to.Original QuestionI am trying to do a simple update of a CalendarFolder using : However , when I call .Update ( ) I get `` The folder save operation failed due to invalid property values . `` I believe that the problem might have something to do with myCalendar not having all of the properties that the calendar folder has on the server . So when I update the object it is only sending a partial object which is causing validation errors.How would I go about updating a CalendarFolder ? After further researchI also stumbled across the following , which does work : I 'm sure there is a difference between the two approaches , but I do n't understand the differences between the folder that I get using the different query methods : and Which approach would give me the correct CalendarFolder where I can set the ExtendedProperties for the room ? <code> var folderId = new FolderId ( WellKnownFolderName.Calendar , new Mailbox ( roomEmail.Address ) ) ; var myCalendar = CalendarFolder.Bind ( service , folderId , PropertySet.FirstClassProperties ) ; myCalendar.DisplayName += `` Updated '' ; myCalendar.Update ( ) ; FindFoldersResults root = service.FindFolders ( WellKnownFolderName.Calendar , new FolderView ( 500 ) ) ; foreach ( var folder in root.Folders ) { folder.DisplayName = `` confRoom1 '' ; folder.Update ( ) ; } new FolderId ( WellKnownFolderName.Calendar , new Mailbox ( roomEmail.Address ) ) ; var myCalendar = CalendarFolder.Bind ( service , folderId , PropertySet.FirstClassProperties ) ; service.FindFolders ( WellKnownFolderName.Calendar , new FolderView ( 500 ) ) ; | Setting ExtendedProperties related to a Room |
C_sharp : Why the following codeprints `` msg '' and this onedoes n't print anything ? <code> class ClassA { public delegate void WriteLog ( string msg ) ; private WriteLog m_WriteLogDelegate ; public ClassA ( WriteLog writelog ) { m_WriteLogDelegate = writelog ; Thread thread = new Thread ( new ThreadStart ( Search ) ) ; thread.Start ( ) ; } public void Search ( ) { /* ... */ m_WriteLogDelegate ( `` msg '' ) ; /* ... */ } } class classB { private ClassA m_classA ; protected void WriteLogCallBack ( string msg ) { // prints msg /* ... */ } public classB ( ) { m_classA = new ClassA ( new WriteLog ( WriteLogCallBack ) ) ; } public void test1 ( ) { Thread thread = new Thread ( new ThreadStart ( Run ) ) ; thread.Start ( ) ; } public void test2 ( ) { m_classA.Search ( ) ; } public void Run ( ) { while ( true ) { /* ... */ m_classA.Search ( ) ; /* ... */ Thread.Sleep ( 1000 ) ; } } } ClassB b = new ClassB ( ) ; b.test2 ( ) ClassB b = new ClassB ( ) ; b.test1 ( ) | A Question About C # Delegates |
C_sharp : Given code similar to the following ( with implementations in the real use case ) : Everything works great with a plain foreach ... e.g . the following compiles fine : We can also compile code to feed all the hungry animals : ... but if we try to use similar code changes to make only the hungry dogs bark , we get a compile errorThis seems like a very strange error , as in fact there is an extension method that can be used . I assume it 's because the compiler considers it ambiguous which generic parameter it needs to use for the Where , and does n't have a specific enough error message for the case of ambiguous generic parameters to the best match extension function.If instead , I were to define AnimalGroup < T > without an interface : The first 3 test cases still work ( because foreach uses the GetEnumerator function even if there 's no interface ) . The error message on the 4th case then moves to the line where it is trying to make an animal ( which happens to be a dog , but which the type system does n't KNOW is a dog ) bark . That can be fixed by changing var to Dog in the foreach loop ( and for completeness using dog ? .Bark ( ) just in case any non-dogs were returned from the enumerator ) .In my real use case , I 'm much more likely to be wanting to deal with AnimalGroup < T > than AnimalGroup ( and it 's actually using IReadOnlyList < T > rather than IEnumerable < T > ) . Making code like cases 2 and 4 work as expected is of far higher priority than allowing Linq functions to be called directly on AnimalGroup ( also desirable for completeness , but of much lower priority ) , so I dealt with it by redefining AnimalGroup without an interface like this : This moves the error to the third case `` feed all the hungry animals '' ( and the error message makes sense in that context - there really is no applicable extension method ) , which I can live with for now . ( Now I think of it , I could have left a non-generic IEnumerable interface on the base class , but this has no benefit , as Linq functions only operate on the generic interface , foreach does n't require it , and callers using IEnumerable would have to cast the result from object ) .Is there some way that I 've not yet thought of , such that I can redefine AnimalGroup and/or AnimalGroup < T > so that all 4 of these test cases compile as expected with the latter 2 directly calling Enumerable.Where ( rather than some other Where function I define ) ? An interesting boundary case is also var genericAnimals = new AnimalGroup < Animal > ; . Uses like genericAnimals.Where ( ... ) compile as expected , even though it is the same class that did n't compile with a different type parameter ! <code> class Animal { public bool IsHungry { get ; } public void Feed ( ) { } } class Dog : Animal { public void Bark ( ) { } } class AnimalGroup : IEnumerable < Animal > { public IEnumerator < Animal > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { throw new NotImplementedException ( ) ; } } class AnimalGroup < T > : AnimalGroup , IEnumerable < T > where T : Animal { public new IEnumerator < T > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } } var animals = new AnimalGroup ( ) ; var dogs = new AnimalGroup < Dog > ( ) ; // feed all the animals foreach ( var animal in animals ) animal.Feed ( ) ; // make all the dogs bark foreach ( var dog in dogs ) dog.Bark ( ) ; // feed all the hungry animals foreach ( var animal in animals.Where ( a = > a.IsHungry ) ) animal.Feed ( ) ; // make all the hungry dogs bark foreach ( var dog in dogs.Where ( d = > d.IsHungry ) ) dog.Bark ( ) ; // error CS1061 : 'AnimalGroup < Dog > ' does not contain a definition for 'Where ' and // no extension method 'Where ' accepting a first argument of type 'AnimalGroup < Dog > ' // could be found ( are you missing a using directive or an assembly reference ? ) class AnimalGroup < T > : AnimalGroup where T : Animal { public new IEnumerator < T > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } } class AnimalGroup { public IEnumerator < Animal > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } } class AnimalGroup < T > : AnimalGroup , IEnumerable < T > where T : Animal { public new IEnumerator < T > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { throw new NotImplementedException ( ) ; } } | Linq functions give strange compile error when ambiguous use of IEnumerable - possible workarounds ? |
C_sharp : I have a small class called Tank has one public member called Location which is a Rectangle ( a struct ) . When I write : everything works fine , and the tank moves.But after I changed the member to be a property , I can no longer use this syntax . It does n't compile , because the t.Location is now a property ( which is function ) and returns a temporary copy of the location ( because it 's a value type ) . The only way I can use Location now is to do something like this : Is there any workaround that can help me not to write this ugly code , and use the intuitive a+=10 ; syntax ? <code> Tank t = new Tank ( ) ; t.Location.X+=10 ; k = t.Location k.X +=10 ; t.Location = k ; | How to work with value types in c # using properties ? |
C_sharp : I 'm trying to port Java code to C # and I 'm running into odd bugs related to the unsigned shift right operator > > > normally the code : Would be the equivalent of Java 's : However for the case of -2147483648L which you might recognized as Integer.MIN_VALUE this returns a different number than it would in Java since the cast to ulong changes the semantics of the number hence I get a different result.How would something like this be possible in C # ? I 'd like to preserve the code semantics as much as possible since its a pretty complex body of code . <code> long l = ( long ) ( ( ulong ) number ) > > 2 ; long l = number > > > 2 ; | Unsigned shift right in C # Using Java semantics for negative numbers |
C_sharp : I noticed that some enumerations have `` None '' as a enumeration member.For example what I meanWhy do they use it ? In what cases solution with a none member is more preferable ( less preferable ) ? <code> enum Mode { Mode1 = 1 , Mode2 = 2 , Mode3 = 3 , None = 4 } | Why do some people use `` None '' as enumeration member ? |
C_sharp : I have a jagged double [ ] [ ] array that may be modified concurrently by multiple threads . I should like to make it thread-safe , but if possible , without locks . The threads may well target the same element in the array , that is why the whole problem arises . I have found code to increment double values atomically using the Interlocked.CompareExchange method : Why is there no overload of Interlocked.Add that accepts Doubles as parameters ? My question is : will it stay atomic if there is a jagged array reference in Interlocked.CompareExchange ? Your insights are much appreciated.With an example : <code> public class Example { double [ ] [ ] items ; public void AddToItem ( int i , int j , double addendum ) { double newCurrentValue = items [ i ] [ j ] ; double currentValue ; double newValue ; SpinWait spin = new SpinWait ( ) ; while ( true ) { currentValue = newCurrentValue ; newValue = currentValue + addendum ; // This is the step of which I am uncertain : newCurrentValue = Interlocked.CompareExchange ( ref items [ i ] [ j ] , newValue , currentValue ) ; if ( newCurrentValue == currentValue ) break ; spin.SpinOnce ( ) ; } } } | Concurrent modification of double [ ] [ ] elements without locking |
C_sharp : In c # 7.0 , you can use discards . What is the difference between using a discard and simply not assigning a variable ? Is there any difference ? <code> public List < string > DoSomething ( List < string > aList ) { //does something and return the same list } _ = DoSomething ( myList ) ; DoSomething ( myList ) ; | What is the difference between discard and not assigning a variable ? |
C_sharp : Normally , with value ( struct ) types , comparison with null ( or object types ) will result in a compiler error.However , if I add equality operator overloads on the struct , the comparison with null no longer produces a compiler error : I believe this has something to do with implicit conversion to Nullable < Value > , but I ca n't remember the details . The question is : Is it possible to overload these operators on a struct while preserving that compiler error ? I 've refactored some code , and I think there are some landmines in the codebase due to this issue . I also worry that future code might accidentally be written in this form , and I 'd really like it to produce a compiler error ( Without having to implement an analyzer ) . <code> struct Value { } class Program { static void Main ( ) { object o = new object ( ) ; Value v = default ; // Error CS0019 Operator '== ' can not be applied to operands of type 'Value ' and ' < null > ' var a = v == null ; // Error CS0019 Operator '== ' can not be applied to operands of type 'Value ' and 'object ' var b = v == o ; } } struct Value { public static bool operator == ( Value l , Value r ) { return true ; } public static bool operator ! = ( Value l , Value r ) { return true ; } } class Program { static void Main ( ) { object o = new object ( ) ; Value v = default ; // compiler is now happy with this . var a = v == null ; // Error CS0019 Operator '== ' can not be applied to operands of type 'Value ' and 'object ' var b = v == o ; } } | Is it possible to suppress implicit conversion from null on a struct with operator overloads ? |
C_sharp : I 'd like your opinion on the following subject : Imagine we have a method that is responsible of achieving one specific purpose , but to do so , it needs the support of an important number of locally scoped objects , many of them implementing IDisposable.MS coding standards say that when using local IDisposable objects that need not `` survive '' the scope of the method ( will not be returned or will not be assigned to the state information of some longer lived object for instance ) you should use the using construct.The problem is , that in some situations you can get a nested `` hell '' of using blocks : You can somehow mitigate this if some of the objects you are using derive from a common base or implement a common interface that implements IDisposable . This of course comes at a cost of having to cast said objects whenever you need the true type of the object . Sometimes this can be viable as long as the amount of casting does n't get out of hand : The other option is not to use using blocks and implement directly try-catch blocks . This would look like : Funny thing , is that VS Code Analyzer will flag this code as `` wrong '' . It will inform you that not all possible execution paths ensure that all disposable objects will be disposed before going out of scope . I can only see that happening if some object throws while disposing which in my opinion should never happen , and if it does , its normally a sign that something really messed up is going on and you are probably better of exiting as fast and gracefully as you can from your entire app.So , the question is : what approach do you like better ? Is it always preferable to use nested using blocks no matter how many , or , past a certain limit , its better to use try-catch block ? <code> using ( var disposableA = new DisposableObjectA ( ) ) { using ( var disposableB = new DisposableObjectB ( ) ) { using ( var disposableC = new DisposableObjectC ( ) ) { //And so on , you get the idea . } } } using ( var disposableA = new DisposableObjectA ( ) ) { using ( DisposableBaseObject disposableB = new DisposableObjectB ( ) , disposableC = new DisposableObjectC ) { using ( var disposableD = new DisposableObjectD ( ) ) { //And so on , you get the idea . } } } DisposableObjectA disposableA = null ; DisposableObjectB disposableB = null ; DisposableObjectC disposableC = null ; ... try { disposableA = new DisposableObjectA ( ) ; ... . } finally { if ( disposableA ! = null ) { disposableA.Dispose ( ) ; } if ( disposableB ! = null ) { disposableB.Dispose ( ) ; } //and so on } | Using block galore ? |
C_sharp : I try to load JPEG file and delete all black and white pixels from imageC # Code : After that I try to find unique colors in List by this codeAnd this code produces different results on different machines on same image ! For example , on this image it produces:43198 unique colors on XP SP3 with .NET version 443168 unique colors on Win7 Ultimate with .NEt version 4.5Minimum test project you can download here . It just opens selected image and produces txt-file with unique colors.One more fact . Some pixels are read differently on different machines . I compare txt-files with notepad++ and it shows that some pixels have different RGB components . The difference is 1 for each component , e.g.Win7 pixel : 255 200 100 WinXP pixel : 254 199 99I have read this post stackoverflow.com/questions/2419598/why-might-different-computers-calculate-different-arithmetic-results-in-vb-net ( sorry , I have n't enough raiting for normal link ) ... .but there was n't information how to fix it . Project was compiled for .NET 4 Client profile on machine with OS Windows 7 in VS 2015 Commumity Edition . <code> ... m_SrcImage = new Bitmap ( imagePath ) ; Rectangle r = new Rectangle ( 0 , 0 , m_SrcImage.Width , m_SrcImage.Height ) ; BitmapData bd = m_SrcImage.LockBits ( r , ImageLockMode.ReadWrite , PixelFormat.Format32bppArgb ) ; //Load Colors int [ ] colours = new int [ m_SrcImage.Width * m_SrcImage.Height ] ; Marshal.Copy ( bd.Scan0 , colours , 0 , colours.Length ) ; m_SrcImage.UnlockBits ( bd ) ; int len = colours.Length ; List < Color > result = new List < Color > ( len ) ; for ( int i = 0 ; i < len ; ++i ) { uint w = ( ( uint ) colours [ i ] ) & 0x00FFFFFF ; //Delete alpha-channel if ( w ! = 0x00000000 & & w ! = 0x00FFFFFF ) //Check pixel is not black or white { w |= 0xFF000000 ; //Return alpha channel result.Add ( Color.FromArgb ( ( int ) w ) ) ; } } ... result.Sort ( ( a , b ) = > { return a.R ! = b.R ? a.R - b.R : a.G ! = b.G ? a.G - b.G : a.B ! = b.B ? a.B - b.B : 0 ; } ) ; List < Color > uniqueColors = new List < Color > ( result.Count ) ; Color rgbTemp = result [ 0 ] ; for ( int i = 0 ; i < len ; ++i ) { if ( rgbTemp == result [ i ] ) { continue ; } uniqueColors.Add ( rgbTemp ) ; rgbTemp = result [ i ] ; } uniqueColors.Add ( rgbTemp ) ; | .NET Bitmap.Load method produce different result on different computers |
C_sharp : Assuming a method with the following signatureWhat is it acceptable for toReturn to be if TryXxxx returns false ? In that it 's infered that toReturn should never be used if TryXxxx fails does it matter ? If toReturn was a nulable type , then it would make sense to return null . But int is n't nullable and I do n't want to have to force it to be.If toReturn is always a certain value if TryXxxx fails we risk having the position where 2 values could be considered to indicate the same thing . I can see this leading to potential possible confusion if the 'default ' value was returned as a valid response ( when TryXxxx returns true ) .From an implementation point if view it looks like having toReturn be a [ ny ] value is easiest , but is there anything more important to consider ? <code> bool TryXxxx ( object something , out int toReturn ) | What 's the standard behaviour for an out parameter when a TryXxxx method returns false ? |
C_sharp : I 've tried to name Button like that : But I 've seen the error : The token `` - Delete '' is unexpectedHow to include < sign in the Content property of Button ? <code> < Button Content= '' < -Delete '' / > | Can I use sign `` < - '' in Content property of Control ? |
C_sharp : Why does the following output provide incorrect result , Output is { N } rather then { 95.00 } as expected . Am I misunderstanding the concept of escaping { } or doing something wrong with Number format ? <code> int myNumber = 95 ; Console.WriteLine ( String.Format ( `` { { { 0 : N } } } '' , myNumber ) ) ; | String.Format does not provide correct result for number format |
C_sharp : Whats the best way to darken a color until it is readable ? I have a series of titles are have an associated color , but some of these colors are very light and any text drawn in them is unreadable . I 've been messing around with HSB and I ca n't seem to get an algorithm down that darkens the color without making it look silverish.I 've basically just been doign this , but it does n't seem to get what I would call `` good '' results : I think I want to alter the saturation too . Is there a standard way of doing this ? <code> Color c = FromHSB ( orig.A , orig.GetHue ( ) , orig.GetSaturation ( ) , orig.GetBrightness ( ) > .9 ? orig.GetBrightness ( ) - MyClass.Random ( .5 , .10 ) : orig.GetBrightness ( ) ) ; | C # Best Way to Darken a Color Until Its Readable |
C_sharp : I seemed to have stumbled upon something unusual within C # that I do n't fully understand . Say I have the following enum defined : If I declare an array of Foo or retrieve one through Enum.GetValues , I 'm able to successfully cast it to both IEnumerable < short > and IEnumerable < ushort > . For example : This happens for other underlying types as well . Arrays of enums always seem to be castable to both the signed and unsigned versions of the underlying integral type.I 'm at a loss for explaining this behavior . Is it well-defined behavior or have I just stumbled onto a peculiar quirk of the language or CLR ? <code> public enum Foo : short { // The values are n't really important A , B } Foo [ ] values = Enum.GetValues ( typeof ( Foo ) ) ; // This cast succeeds as expected.var asShorts = ( IEnumerable < short > ) values ; // This cast also succeeds , which was n't expected.var asUShorts = ( IEnumerable < ushort > ) values ; // This cast fails as expected : var asInts = ( IEnumerable < int > ) values ; | Why can enum arrays be cast to two different IEnumerable < T > types ? |
C_sharp : I 'm writing Android application that connect with ASP.net web service ( C # ,3.5 ) android Application send `` Sign in '' information of the user to web service to verify that if the user is registered or not.here is the [ WebMethod ] which receive the request : SigninPerson is a class which hold user information like First Name , Last Name , Password ... .the problem is in the password comparison . it accepted all the cases for example : if the password for somebody which stored in DataBase is `` ABD '' , and the user entered `` abd '' as password , the application accepted it ! ( not Case sensitive ! ! ! ) how to solve this problem ? <code> [ WebMethod ] public SigninPerson signin ( SigninPerson SIPerson ) { SigninPerson Temp = new SigninPerson ( 0 , `` '' , `` '' , `` '' , `` '' ) ; LinqToSQLDataContext DataBase = new LinqToSQLDataContext ( ) ; var Person = ( from a in DataBase.Persons where a.Email == SIPerson.E_Mail & & a.Password.Equals ( SIPerson.Password , StringComparison.Ordinal ) select new SigninPerson { Person_Id = a.Person_Id , F_Name = a.First_Name , L_Name = a.Last_Name , E_Mail = a.Email , Password = a.Password } ) ; if ( Person.Any ( ) == true ) { Temp = Person.FirstOrDefault ( ) ; } return Temp ; } | String Comparsion in ASP.net ( C # ) |
C_sharp : We have to use api from 3rd party vendor ( perforce ) . Till today , we were able to reference and use that API in .net framework application . But , now we are refactoring our product and of course we decided to use new .net environment , which is .net core 2.2 . As , Perforce did n't publish that library for .net core , we decided to port that library to .net standard . So , in a nutshell we downloaded source code , ported , and added as a reference in .net core project . So far , so good . A weird thing is that , after some usage of that library we are getting ExecutionEngineException from that library , which triggers Environment.Failfast and terminates application.One more important information is that library uses another native library ( p4bridge.dll ) .The exception is so : I am already aware of the message related to garbage collected delegate . It seems , at some place pointer to the delegate is passed to unmanaged library and then GC collected it.We take a look to the source code of that api . And we saw some possible places which can be reason for that error . But , this is just a thought . While investigating the failure , we created another .net framework application which references to that ported library , and then we did n't came across any error in .net framework.My questions are : Is there any difference between .net framework and .net core in terms of garbage collector mechanism ? How is that possible that , .net framework and .net core reacts to the same library in a different ways ? <code> FailFast : A callback was made on a garbage collected delegate of type 'p4netapi ! Perforce.P4.P4CallBacks+LogMessageDelegate : :Invoke ' . at Perforce.P4.P4Bridge.RunCommandW ( IntPtr , System.String , UInt32 , Boolean , IntPtr [ ] , Int32 ) at Perforce.P4.P4Bridge.RunCommandW ( IntPtr , System.String , UInt32 , Boolean , IntPtr [ ] , Int32 ) at Perforce.P4.P4Server.RunCommand ( System.String , UInt32 , Boolean , System.String [ ] , Int32 ) at Perforce.P4.P4Command.RunInt ( Perforce.P4.StringList ) at Perforce.P4.P4CommandResult..ctor ( Perforce.P4.P4Command , Perforce.P4.StringList ) at Perforce.P4.P4Command.Run ( Perforce.P4.StringList ) at Perforce.P4.Client.runFileListCmd ( System.String , Perforce.P4.Options , System.String , Perforce.P4.FileSpec [ ] ) at Perforce.P4.Client.SyncFiles ( System.Collections.Generic.IList ` 1 < Perforce.P4.FileSpec > , Perforce.P4.Options ) | .net standard library fails in .net core but not in framework |
C_sharp : I wrote some code today and It was changed by another developer who said it was more safe . I am not sure this is right as I can not see the advantage of what was done here are some code examplesthis was changed toI am quite new to c # should the stream not be closed when you are finished with it ? <code> public byte [ ] ReadFile ( Stream stream ) { byte [ ] result = null ; try { // do something with stream result = < result of operation > } finally { stream.Close ( ) ; } return result ; } public byte [ ] ReadFile ( Stream stream ) { byte [ ] result = null ; // do something with stream result = < result of operation > return result ; } | Closing a stream in function , a bad idea ? |
C_sharp : I have a propertygrid which I need to create a combobox inside the propertygrid and display int value ( 1 to 9 ) , I found using enum is the easiest way , but enum could n't display int value , even I try to cast it to int , but I do not know how to return all the value . Any other way to do this ? Thanks in Advance . Below is my code . <code> public class StepMode { private TotalSteps totalSteps ; public TotalSteps totalsteps { get { return totalSteps ; } set { value = totalSteps ; } } public enum TotalSteps { First = 1 , Second = 2 , Three = 3 , Four = 4 , Five = 5 , Six = 6 , Seven = 7 , Eight = 8 , Nine = 9 } } | display int value from enum |
C_sharp : I have an issue looping the if-statement in my code . I looked at other threads on stackoverflow but I could n't get it to work multiple times . The program I 'm trying to create is a basic converter for a casting company . What I tried to do is make it so that the user can input the type of conversion needed then the weight of the wax . It would then give the user the correct amount of grams of precious metal to use . The issue is that I need it to run from the beginning until the user is done using it . I tried using a while statement but it just loops the else part of the if-statement . Here 's my code for reference : I realize that a good programmer does n't type the same code twice but I 'm just not at that level yet , I just want the code to loop . Would I have to make it a big nested if-statement ? <code> static void Main ( string [ ] args ) { double waxWeight , bronzeWeight , silverWeight , fourteenkGoldWeight , eighteenkGoldWeight , twentytwokGoldWeight , platinumWeight ; string wW ; bool doesUserWantToLeave = false ; Console.WriteLine ( `` Please specify the type of conversion you would like to accomplish : '' + `` \n ( Bronze , Silver , 14k Gold , 18k Gold , 22k Gold , Platinum , or Exit ) : '' ) ; string conversionType = Console.ReadLine ( ) ; //bool B = conversionType == `` Bronze '' ; //bool S = conversionType == `` Silver '' ; //bool ftG = conversionType == `` 14k Gold '' ; //bool etG = conversionType == `` 18k Gold '' ; //bool ttG = conversionType == `` 22k Gold '' ; //bool P = conversionType == `` Platinum '' ; while ( ! doesUserWantToLeave ) { if ( conversionType == `` Bronze '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; bronzeWeight = waxWeight * 10 ; Console.WriteLine ( `` You need `` + bronzeWeight + `` grams of bronze . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` Silver '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; silverWeight = waxWeight * 10.5 ; Console.WriteLine ( `` You need `` + silverWeight + `` grams of silver . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` 14k Gold '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; fourteenkGoldWeight = waxWeight * 13.5 ; Console.WriteLine ( `` You need `` + fourteenkGoldWeight + `` grams of 14 Karat gold . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` 18k Gold '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; eighteenkGoldWeight = waxWeight * 15 ; Console.WriteLine ( `` You need `` + eighteenkGoldWeight + `` grams of 18 Karat gold . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` 22k Gold '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; twentytwokGoldWeight = waxWeight * 17.3 ; Console.WriteLine ( `` You need `` + twentytwokGoldWeight + `` grams of 22 Karat gold . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` Platinum '' ) { Console.WriteLine ( `` What is the weight of the wax model ? `` ) ; wW = Console.ReadLine ( ) ; waxWeight = double.Parse ( wW ) ; platinumWeight = waxWeight * 21.5 ; Console.WriteLine ( `` You need `` + platinumWeight + `` grams of platinum . `` ) ; Console.ReadLine ( ) ; } else if ( conversionType == `` Exit '' ) { doesUserWantToLeave = true ; } else { Console.WriteLine ( `` Sorry ! That was an invalid option ! `` ) ; Console.ReadLine ( ) ; } } } | How to loop an if-statement with many else if conditions |
C_sharp : I 'm learning C # generics and making some dummy code for testing purposes . So , I 'm testing the in Generic Modifier , which specifies that the type parameter is contravariant.Given the below interface : When compiling , I 'm getting the error message : [ CS1961 ] Invalid variance : The type parameter 'T ' must be invariantly valid on 'IInterfaceTest.Method ( IList ) ' . 'T ' is contravariant.The error is related only with the line void Method ( IEnumerable < T > values ) . If this line is removed , all works fine.So my question is : Why can I use the generic contravariant with IEnumerable but does not with IList ? Am I forgot something ? Thanks . <code> public interface IInterfaceTest < in T > { void Method ( T value ) ; void Method ( IList < T > values ) ; void Method ( IEnumerable < T > values ) ; } | Using generic contravariant with IList and IEnumerable |
C_sharp : I got two sets of numbers , with SET2 having more items in it usually . It 's guaranteed that the count of SET2 is equal or greater than the count of SET1 . Acutally , since the order matters the input are rather lists than sets.My goal is to combine ( sum up ) / reorder the numbers from SET2 to make it as similar to SET1 as possible . I define the similarity as the sum of the deviations at every position . See this post for the way I calculate the similarity . The smaller the sum , the better . My first approach was to try all combinations and pick the best one . This only works for quite small sets ( esp . the second one ) . See this post and the answer from Rawling . Is there a smarter way to get a good combination ? I definitely do n't need the best one . A good one would be fine as a result . Obviously a sets with empty subsets are nonsense . Extremly unbalanced sets do n't seem to be very promising to me . SET1 tends to have about 8 but can have up to 18 entries . SET2 has often a count of more than 10 ( up to 35 ) .The sum of the numbers in the two sets is equal ( except for rounding errors ) . Here is an example with good and bad results ( not all possible ones ) : Please let me know if I forgot to describe a premiss or my description is unclear or even faulty . I 'm also happy to provide another example . Thanks in advance ! <code> SET1 = { 272370 , 194560 , 233430 } ; SET2 = { 53407.13 , 100000 , 365634.03 , 181319.07 } 272370 | 194560 | 233430 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 365634.03 | 100000 + 53407.13 | 181319.07 ( best match ) 365634.03 | 181319.07 | 100000 + 53407.13 ( good ) 365634.03 | 100000 |181319.07 + 53407.13 ( ok ) 53407.13 |365634.03 + 100000 | 181319.07 ( bad ) 53407.13 |365634.03 + 181319.07 | 100000 ( bad ) . |365634.03 + 181319.07 | 53407.13 + 100000 ( invalid ) 53407.13 + 100000 |365634.03 + 181319.07 | ( invalid ) | Finding a good match of two lists of numbers |
C_sharp : I have couple of classes that are identified by some ID ( which is unique integer for every class ) . Next I need a method which takes an integer ( ID ) as argument and return corresponding class type . So far I have come to this : For now it seems that it works , but for some reason I do n't like that I have to instantiate the class to get its type . Could this cause any problems ? Another solution I found is to use Type.GetType ( classNameAsString ) method , but I guess this could cause some runtime errors or bugs in case class name is changed ( i.e . I change the name of class , but forgot to update the GetById method ) .Is there some better way to do this ? <code> public static Type GetById ( int id ) { switch ( id ) { case 1 : return ( new ClassA ( ) ) .GetType ( ) ; case 2 : return ( new ClassB ( ) ) .GetType ( ) ; case 3 : return ( new ClassC ( ) ) .GetType ( ) ; // ... and so on } } | C # method to return a type |
C_sharp : I was reading a C # book in which the author ( some dude named Jon Skeet ) implements a Where function like Now , I fully understand how this works and that it 's equivalent to which brings up the question of why would one separate these into 2 functions given that there would be memory/time overhead and of course more code . I always validate parameters and if I start writing like this example then I 'll be writing twice as much code . Is there some school of thought which holds that validation and implementation should be separate functions ? <code> public static IEnumerable < T > Where < T > ( this IEnumerable < T > source , Funct < T , bool > predicate ) { if ( source == null || predicate == null ) { throw new ArgumentNullException ( ) ; } return WhereImpl ( source , predicate ) ; } public static IEnumerable < T > WhereImpl < T > ( IEnumerable < T > source , Func < T , bool > predicate ) { foreach ( T item in source ) { if ( predicate ( item ) ) { yield return item ; } } } public static IEnumerable < T > Where < T > ( this IEnumerable < T > source , Funct < T , bool > predicate ) { if ( source == null || predicate == null ) { throw new ArgumentNullException ( ) ; } foreach ( T item in source ) { if ( predicate ( item ) ) { yield return item ; } } } | Separate functions into validation and implementation ? Why ? |
C_sharp : I need to continuously read a log file to detect certain patterns . How can do so without interfering with file operations that the log writer operation needs to perform ? The log writer process , in addition to writing logs , periodically moves the file to another location ( one it reaches certain size ) .With the way I read the file , the log writer app fails to move the file . I played with various FileShare options to no avail.Here 's simplified version of my code : <code> using ( FileStream stream = new FileStream ( @ '' C : \temp\in.txt '' , FileMode.Open , FileAccess.Read , FileShare.Delete ) ) { TextReader tr = new StreamReader ( stream ) ; while ( true ) { Console.WriteLine ( `` .. `` + tr.ReadLine ( ) ) ; Thread.Sleep ( 1000 ) ; } } | Read a file in such a way that other processes are not prevented from modifying it |
C_sharp : My colleague and I came across this when looking into getting the invocation list of a delegate . If you create an event in say class X , then you can access the public methods of the event fine from within that class . But ( and please ignore stuff like why you 'd have public access to class members , this is n't what we 're asking ! ) , if we have a class Y instantiating X , and accessing the event within X , it ca n't call any of the public methods such as GetInvocationList ( ) of the event . We wanted to know how this works . Here is a code sample ( read the comments to see what we mean ) : Out of curiosity how do you achieve this , and what 's the reason for having this feature avaialble ? Many Thanks Amit <code> public class X { public delegate void TestMethod ( ) ; public event TestMethod testMethod ; private void rubbish ( ) { // can access testMethod.GetInvocationList ( ) fine here testMethod.GetInvocationList ( ) ; } } public class Y { public Y ( ) { X x = new X ( ) ; x.testMethod += this.test ; // here it says testMethod can only appear on the left hand side of += or -= // why is this ? ( i.e . the below line is invalid ) x.testMethod.GetInvocationList ( ) ; } public void test ( ) { } } | How to make public methods only visible in class itself and class owning the object in C # ? |
C_sharp : Boxed nullable underlying type can be cast to enum but boxed enum type ca n't be cast to nullable type.And similarly , Boxed nullable enum can be cast to underlying type but boxed underlying type ca n't be cast to nullable enum.Ok , I know `` boxed nullable type '' is not the best way to describe it , but it 's for the sake of the question . I 'm aware it 's the underlying value type that 's getting boxed.I will show it with examples . Assume I have an enum with int as the underlying type.Case I : Case II : In a nutshell , Or in even simpler terms , cast to non-nullable - > succeeds cast to nullable - > failsNow I do know that once you box a value type , it can be cast back only to the original type . But since by C # rules , a boxed int can be cast to enum and a boxed enum can be cast to int , and a boxed int to int ? and a boxed int ? to int , I was looking for a consistent understanding of other scenarios as well , ie the ones listed above . But I dont get the logic . For one , I feel if they all failed or if they all succeeded , it made more sense to developers . Two , even the successful casts look a little odd . I mean since a value type can be implicitly cast to its nullable equivalent ( and not the other way around ) , a cast to nullable should anyway succeed , but with the current implementation a nullable type is being successfully cast to non-nullable which can even fail if the former had a null value . Had this whole thing been other way around , it would have been easier comprehending . An example like : Questions : So what C # rule is letting this happen ? Is there a simple way I can remember this ? <code> enum Sex { Male , Female } int ? i = 1 ; object o = i ; Sex e = ( Sex ) o ; //success//butSex e = Sex.Male ; object o = e ; int ? i = ( int ? ) o ; //invalid cast Sex ? e = Sex.Male ; object o = e ; int i = ( int ) o ; //success//butint i = 1 ; object o = i ; Sex ? e = ( Sex ? ) o ; //invalid cast ( enum ) int ? - > succeeds ( int ? ) enum - > the reverse fails ( int ) enum ? - > succeeds ( enum ? ) int - > the reverse fails Sex ? e = null ; object o = e ; int i = ( int ) o ; //succeeds , but sure to explode on cast//butint i = 1 ; object o = i ; Sex ? e = ( Sex ? ) o ; //invalid cast , even though its always a safe cast | Boxed nullable underlying type can be cast to enum but boxed enum type ca n't be cast to nullable type |
C_sharp : This code after compilation looks like this in ILSpy : Why does it happen and can it be the reason of regex not matching in .Net 3.5 ? On 4.5 it works . <code> Regex regex = new Regex ( `` blah '' , RegexOptions.Singleline & RegexOptions.IgnoreCase ) ; Regex regex = new Regex ( `` blah '' , RegexOptions.None ) ; | Why RegexOptions are compiled to RegexOptions.None in MSIL ? |
C_sharp : I have the following simple codeWhen I ran this code the line Test ( ( Int32 ) 1 ) causes stack overflow due to infinite recursion . The only possible way to correctly call proper method ( with integer parameter ) I found isBut this is not appropriate for me , because both methods Test are public and I am willing the users to be able to call both method ? <code> abstract class A { public abstract void Test ( Int32 value ) ; } class B : A { public override void Test ( Int32 value ) { Console.WriteLine ( `` Int32 '' ) ; } public void Test ( Double value ) { Test ( ( Int32 ) 1 ) ; } } ( this as A ) .Test ( 1 ) ; | How to call overridden method which have overloads ? |
C_sharp : I want to generate triangles from points and optional relations between them . Not all points form triangles , but many of them do.In the initial structure , I 've got a database with the following tables : Nodes ( id , value ) Relations ( id , nodeA , nodeB , value ) Triangles ( id , relation1_id , relation2_id , relation3_id ) In order to generate triangles from both nodes and relations table , I 've used the following query : It 's working perfectly on small sized data . ( ~ < 50 points ) In some cases however , I 've got around 100 points all related to each other which leads to thousands of relations . So when the expected number of triangles is in the hundreds of thousands , or even in the millions , the query might take several hours.My main problem is not in the select query , while I see it execute in Management Studio , the returned results slow . I received around 2000 rows per minute , which is not acceptable for my case.As a matter of fact , the size of operations is being added up exponentionally and that is terribly affecting the performance.I 've tried doing it as a LINQ to object from my code , but the performance was even worse.I 've also tried using SqlBulkCopy on a reader from C # on the result , also with no luck.So the question is ... Any ideas or workarounds ? <code> INSERT INTO TrianglesSELECT t1.id , t2.id , t3.id , FROM Relations t1 , Relations t2 , Relations t3WHERE t1.id < t2.id AND t3.id > t1.id AND ( t1.nodeA = t2.nodeA AND ( t3.nodeA = t1.nodeB AND t3.nodeB = t2.nodeBOR t3.nodeA = t2.nodeB AND t3.nodeB = t1.nodeB ) OR t1.nodeA = t2.nodeBAND ( t3.nodeA = t1.nodeB AND t3.nodeB = t2.nodeAOR t3.nodeA = t2.nodeA AND t3.nodeB = t1.nodeB ) ) | Forming triangles from points and relations |
C_sharp : I 'm processing lots of data in a 3D grid so I wanted to implement a simple iterator instead of three nested loops . However , I encountered a performance problem : first , I implemented a simple loop using only int x , y and z variables . Then I implemented a Vector3I structure and used that - and the calculation time doubled . Now I 'm struggling with the question - why is that ? What did I do wrong ? Example for reproduction : What I measured : Note : the 'IteratedVectorAvoidNew ' is there due to discussion that the problem might lie in the new operator of Vector3I - originally , I used a custom iteration loop and measured with a stopwatch.Additionally , a benchmark of when I iterate over a 256×256×256 area : My environment : Intel ( R ) Core ( TM ) 2 Quad CPU Q6600 @ 2.40GHzWindows 10 , 64 bitVisual Studio 2017Language : C # Yes , I selected Release configurationNotes : My current task is to rewrite existing code to a ) support more features , b ) be faster . Also I 'm working on lots of data - this is the current bottleneck of the whole application so no , it 's not a premature optimization.Rewriting nested loops into one - I 'm not trying to optimize there . I just need to write such iterations many times , so simply wanted to simplify the code , nothing more . But because it 's a performance-critical part of the code , I 'm measuring such changes in design . Now , when I see that simply by storing three variables into a struct I double the processing time ... I 'm quite scared of using structs like that ... <code> using BenchmarkDotNet.Attributes ; using BenchmarkDotNet.Running ; using System.Runtime.CompilerServices ; public struct Vector2I { public int X ; public int Y ; public int Z ; [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public Vector2I ( int x , int y , int z ) { this.X = x ; this.Y = y ; this.Z = z ; } } public class IterationTests { private readonly int _countX ; private readonly int _countY ; private readonly int _countZ ; private Vector2I _Vector = new Vector2I ( 0 , 0 , 0 ) ; public IterationTests ( ) { _countX = 64 ; _countY = 64 ; _countZ = 64 ; } [ Benchmark ] public void NestedLoops ( ) { int countX = _countX ; int countY = _countY ; int countZ = _countZ ; int result = 0 ; for ( int x = 0 ; x < countX ; ++x ) { for ( int y = 0 ; y < countY ; ++y ) { for ( int z = 0 ; z < countZ ; ++z ) { result += ( ( x ^ y ) ^ ( ~z ) ) ; } } } } [ Benchmark ] public void IteratedVariables ( ) { int countX = _countX ; int countY = _countY ; int countZ = _countZ ; int result = 0 ; int x = 0 , y = 0 , z = 0 ; while ( true ) { result += ( ( x ^ y ) ^ ( ~z ) ) ; ++z ; if ( z > = countZ ) { z = 0 ; ++y ; if ( y > = countY ) { y = 0 ; ++x ; if ( x > = countX ) { break ; } } } } } [ Benchmark ] public void IteratedVector ( ) { int countX = _countX ; int countY = _countY ; int countZ = _countZ ; int result = 0 ; Vector2I iter = new Vector2I ( 0 , 0 , 0 ) ; while ( true ) { result += ( ( iter.X ^ iter.Y ) ^ ( ~iter.Z ) ) ; ++iter.Z ; if ( iter.Z > = countZ ) { iter.Z = 0 ; ++iter.Y ; if ( iter.Y > = countY ) { iter.Y = 0 ; ++iter.X ; if ( iter.X > = countX ) { break ; } } } } } [ Benchmark ] public void IteratedVectorAvoidNew ( ) { int countX = _countX ; int countY = _countY ; int countZ = _countZ ; int result = 0 ; Vector2I iter = _Vector ; iter.X = 0 ; iter.Y = 0 ; iter.Z = 0 ; while ( true ) { result += ( ( iter.X ^ iter.Y ) ^ ( ~iter.Z ) ) ; ++iter.Z ; if ( iter.Z > = countZ ) { iter.Z = 0 ; ++iter.Y ; if ( iter.Y > = countY ) { iter.Y = 0 ; ++iter.X ; if ( iter.X > = countX ) { break ; } } } } } } public static class Program { public static void Main ( string [ ] args ) { BenchmarkRunner.Run < IterationTests > ( ) ; } } Method | Mean | Error | StdDev | -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | NestedLoops | 333.9 us | 4.6837 us | 4.3811 us | IteratedVariables | 291.0 us | 0.8792 us | 0.6864 us | IteratedVector | 702.1 us | 4.8590 us | 4.3073 us | IteratedVectorAvoidNew | 725.8 us | 6.4850 us | 6.0661 us | Method | Mean | Error | StdDev | -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | NestedLoops | 18.67 ms | 0.0504 ms | 0.0446 ms | IteratedVariables | 18.80 ms | 0.2006 ms | 0.1877 ms | IteratedVector | 43.66 ms | 0.4525 ms | 0.4232 ms | IteratedVectorAvoidNew | 43.36 ms | 0.5316 ms | 0.4973 ms | | Why is using structure Vector3I instead of three ints much slower in C # ? |
C_sharp : I know that we can use a format specifier for string interpolation in C # 6However I am using the same format in the same method over and over again so would like to soft code it , but not sure how to do it , or even if its possible , Can someone tell me how to do it , or confirm to me its impossible as I have done some reading and found nothing to suggest its possible <code> var someString = $ '' the date was ... { _criteria.DateFrom : dd-MMM-yyyy } '' ; DateTime favourite ; DateTime dreaded ; ... ... const string myFormat = `` dd-MMM-yyyy '' ; var aBigVerbatimString = $ @ '' my favorite day is { favourite : $ myFormat } but my least favourite is { dreaded : $ myFormat } blah blah `` ; | Soft coding format specifier for Interpolated strings c # 6.0 |
C_sharp : I 've got some code that has an awful lot of duplication . The problem comes from the fact that I 'm dealing with nested IDisposable types . Today I have something that looks like : The whole nested using block is the same for each of these methods ( two are shown , but there are about ten of them ) . The only thing that is different is what happens when you get to the inner level of the using blocks.One way I was thinking would be to do something along the lines of : This works , it 's just kind of clunky to parse ( as a human ) . Does anyone have any other suggestions on how one could reduce the code duplication around nested using blocks like this ? If they were n't IDisposable then one would likely just create a method to return the results of b.GetC ( innerId ) ... but that is n't the case here . <code> public void UpdateFromXml ( Guid innerId , XDocument someXml ) { using ( var a = SomeFactory.GetA ( _uri ) ) using ( var b = a.GetB ( _id ) ) using ( var c = b.GetC ( innerId ) ) { var cWrapper = new SomeWrapper ( c ) ; cWrapper.Update ( someXml ) ; } } public bool GetSomeValueById ( Guid innerId ) { using ( var a = SomeFactory.GetA ( _uri ) ) using ( var b = a.GetB ( _id ) ) using ( var c = b.GetC ( innerId ) ) { return c.GetSomeValue ( ) ; } } public void UpdateFromXml ( Guid innerId , XDocument someXml ) { ActOnC ( innerId , c = > { var cWrapper = new SomeWrapper ( c ) ; cWrapper.Update ( someXml ) ; } ) ; } public bool GetSomeValueById ( Guid innerId ) { var result = null ; ActOnC ( innerId , c = > { result = c.GetSomeValue ( ) ; } ) ; return result ; } private void ActOnC ( Guid innerId , Action < TheCType > action ) { using ( var a = SomeFactory.GetA ( _uri ) ) using ( var b = a.GetB ( _id ) ) using ( var c = b.GetC ( innerId ) ) { action ( c ) ; } } | How could one refactor code involved in nested usings ? |
C_sharp : I work with resharper and when I clean my code I get this layout : I 'd rather have : is this possible ? <code> mock.Setup ( m = > m.Products ) .Returns ( new List < Product > { new Product { Name = `` Football '' , Price = 25 } , new Product { Name = `` Surf board '' , Price = 179 } , new Product { Name = `` Running Shoes '' , Price = 95 } } .AsQueryable ( ) ) ; mock.Setup ( m = > m.Products ) .Returns ( new List < Product > { new Product { Name = `` Football '' , Price = 25 } , new Product { Name = `` Surf board '' , Price = 179 } , new Product { Name = `` Running Shoes '' , Price = 95 } } .AsQueryable ( ) ) ; | resharper inline object initialisation |
C_sharp : I want to perform the updation of the existing record.. the way that i have paste my code here i have successfully achieved my task but i dont want to do the updation by that way actually.. i want to do such that i get the id of the customer.. <code> private void btnUpdate_Click ( object sender , EventArgs e ) { SqlConnection cn = new SqlConnection ( @ '' Data Source=COMPAQ-PC-PC\SQLEXPRESS ; Initial Catalog=Gym ; Integrated Security=True '' ) ; if ( cn.State == ConnectionState.Closed ) { cn.Open ( ) ; } int result = new SqlCommand ( `` Update Customer set Customer_Name = ' '' + tbName.Text + `` ' , Cell_Number = ' '' + tbContactNumber.Text + `` ' , Customer_Address = ' '' + tbAddress.Text + `` ' where CustomerID = `` + tbID.Text , cn ) .ExecuteNonQuery ( ) ; if ( cn.State == ConnectionState.Open ) { cn.Close ( ) ; } cn.Dispose ( ) ; BindGridView ( ) ; } private void BindGridView ( ) { SqlConnection cn = new SqlConnection ( @ '' Data Source=COMPAQ-PC-PC\SQLEXPRESS ; Initial Catalog=Gym ; Integrated Security=True '' ) ; SqlCommand cmd = new SqlCommand ( `` Select * from Customer '' , cn ) ; SqlDataAdapter da = new SqlDataAdapter ( cmd ) ; DataTable dt = new DataTable ( ) ; da.Fill ( dt ) ; dgView_CustomerInfo.DataSource = dt.DefaultView ; } private void dgView_CustomerInfo_RowHeaderMouseClick ( object sender , DataGridViewCellMouseEventArgs e ) { tbID.Text = dgView_CustomerInfo.Rows [ e.RowIndex ] .Cells [ `` CustomerID '' ] .Value.ToString ( ) ; tbName.Text = dgView_CustomerInfo.Rows [ e.RowIndex ] .Cells [ `` Customer_Name '' ] .Value.ToString ( ) ; tbContactNumber.Text = dgView_CustomerInfo.Rows [ e.RowIndex ] .Cells [ `` Cell_Number '' ] .Value.ToString ( ) ; tbAddress.Text = dgView_CustomerInfo.Rows [ e.RowIndex ] .Cells [ `` Customer_Address '' ] .Value.ToString ( ) ; } | A question regarding C # and SQL |
C_sharp : consider the variable ob4 as shown in figurenow : how can i reach ob4 [ 0 ] - > [ 0,2 ] the line ( double [ , ] p= ( double [ , ] ) o [ 0,0 ] ; ) gives the following error : Can not apply indexing with [ ] to an expression of type 'object ' <code> var o=ob4 [ 0 ] ; double [ , ] p= ( double [ , ] ) o [ 0,0 ] ; | Working with object |
C_sharp : I have a WinForms project which is several years old and has been retro-fitted with async event-handlers : Inside this method is an async call : When the program runs on a normal resolution screen , it runs as expected . However , when run on a high-DPI screen the window 's dimensions - as well as those of all child controls - jump to half-size as soon as it encounters that inner async call . It 's as if the program is suddenly run in a compatibility mode or the scaling has been disabled.Currently , in an effort to debug the problem , the GetProjectTemplateFile method consists simply ofIt makes no difference whether GetProjectTemplateFile performs an async operation or not.If I comment-out that async call to GetProjectTemplateFile then the program runs as expected without any jump in dimensions , even though there are still other async calls made in the CellClick event.I 've tried appending .ConfigureAwait ( true ) to the async call , which makes no difference . Nor does running the call synchronously with .GetAwaiter ( ) .GetResult ( ) .Can anyone explain why the window 's dimensions are changing with this particular async call , and/or how to prevent this from happening ? UpdateAs per a request , here is a code sample which elicits the explained behaviour . There 's nothing unusual happening here that I can see but I assure you , this very code is causing the explained behaviour.Some other information which might be relevant : The FormBorderStyle of the window is `` FixedToolWindow '' The window is given an explicit width in a startup methodAutoSize = FalseAutoSizeMode = GrowOnlyThe computer which it 's being developed on does not have the Windows 10 1703 ( Creator 's ) update which has new scaling logicIf the GetprojectTemplateFile method is not async , i.e . has signature public ProjectTemplateFile GetProjecttemplateFile ( ... ) then there is no problem . This problem appears to exist only when the method call is async - even if I make it a blocking call.UPDATE 2 : I 've found the specific line ( s ) of code which cause this problem : The inner async call , GetProjectTemplateFile , calls an API and then checks the response : If I comment-out the MessageBox.Show ( ... ) call then everything is normal , no scaling problems , no jump in dimensions.But the problem occurs when the MessageBox.Show ( ... ) call is in-place.Furthermore , the API responds with a 200 ( OK ) so the MessageBox code is n't even being used . My guess is that the JIT compiler sees it as a possibility so ... it re-renders the form ? Also , importantly , this code is not in the form 's code-behind , it 's in a class which the form is given an instance of in its constructor . <code> private async void dgvNewOrders_CellClick ( object sender , DataGridViewCellEventArgs e ) var projectTemplate = await GetProjectTemplateFile ( companyId , sourceLang , targetLang ) ; private async Task < ProjectTemplateFile > GetProjectTemplateFile ( long companyId , string sourceLanguage , string targetLanguage ) { return null ; } private async void dgvNewOrders_CellClick ( object sender , DataGridViewCellEventArgs e ) { var result = await _templateInteraction.GetProjectTemplateFile ( 1 , `` en-US '' , `` de-CH '' ) ; return ; } public class TemplateInteraction : ITemplateInteraction { public async Task < ProjectTemplateFile > GetProjectTemplateFile ( long companyId , string sourceLanguage , string targetLanguage ) { return null ; // elided code } // other methods } MessageBox.Show ( ... ) ; var responseMessage = await client.GetAsync ( uri ) ; if ( ! responseMessage.IsSuccessStatusCode ) { MessageBox.Show ( ... ) ; return null ; } | WinForms window changes dimensions when it encounters an async call |
C_sharp : I got a little problem with reading information from an xml file ... The file passed to me has thousands of lines . Im interested in only 300 - 400 of those lines . I do n't need to write any data back to xml when the user is finished with his operation and the data to read can be stored in a List < string > .I found solutions on the net using an XmlTextReader to read the data . So I wouldnt have to create a class and use a Serializer . But it seems like im using the XmlTextReader wrong . Maybe you can help me ... This is how the xml looks like : I 'm only interested in the Value of the most inner Name Elements ( The first two would be `` 098-0031 '' and `` 098-0032 '' ) .And this is my code : But the condition reader.Name == `` Children '' is never fullfilled ... Can someone explain to me why . And maybe show me an easy way to store those values in a List < string > ? Thanks in advance ! EDIT : I edited the xml . Sorry for that but its really hard to filter the unnecassary confusing parts from my xml ... <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ProjectConfiguration xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < ProjectLists xmlns= '' ... '' > < ProjectList > ... // not interested in this data < /ProjectList > < ProjectList > < ListNode > < Name > Test_Environment < /Name > < Children > < ListNode > < Name > yyy < /Name > < Children > < ListNode > < Name > 205 ( ST ) < /Name > < Children > < ListNode > < Name > 098-0031 < /Name > < Children / > < /ListNode > < ListNode > < Name > 098-0032 < /Name > < Children / > < /ListNode > //more ListNodes ... < /Children > < /ListNode > < ListNode > < Name > old < /Name > < Children > < ListNode > < Name > W098-32 < /Name > < Children / > < /ListNode > < /Children > < /ListNode > < /Children > < /ListNode > < ListNode > < Name > xxx < /Name > < Children / > < /ListNode > < ListNode > < Name > 098-0001 < /Name > < Children / > < /ListNode > < ListNode > < Name > 098-0011 < /Name > < Children / > < /ListNode > // More List Nodes < /Children > < /ListNode > < ListNode > // more List Nodes < /ListNode > < /ProjectList > < ProjectList > //more uninteresting ProjectLists ... < /ProjectList > while ( reader.Read ( ) ) { switch ( reader.NodeType ) { case XmlNodeType.Element : { if ( reader.Name == `` Name '' ) { reader.Read ( ) ; if ( reader.Value == `` Test_Environment '' ) { reader.ReadToDescendant ( `` Children '' ) ; if ( reader.Name == `` Children '' ) { reader.ReadToDescendant ( `` Children '' ) ; } } } } break ; } } | Read xml from file |
C_sharp : I 've got a number of classes designed to handle objects of specific types.e.g. , where the handler interface might be defined something like this : Now , I 'd like to be able to use a dictionary of these handlers : However , C # does n't appear to allow me to use the Handler interface without specifying a type . C # also does n't allow me to declare interface Handler < out T > so I ca n't use Handler < object > in the handlers declaration . Even this does n't work : This seems to be solvable using reflection : And , of course , I could remove the generics from the Handler interface . However , the reason I went down this path is that I wanted to make the API for handlers as simple as possible . I wanted classes to specify the messages they receive and for them to be able to process those messages without having to cast the parameters in every method.I 'd prefer to avoid reflection if possible and avoiding generics altogether does n't quite seem satisfactory.Am I missing something obvious or am I pushing up against the limits of C # 's generics ? I realize that C # is n't Java ( with Java 's type erasure , this would be easy ) and perhaps this might have been better solved in a more C # -like way ... so I 'm also interested in other approaches.Thanks ! <code> class FooHandler : Handler < Foo > { void ProcessMessage ( Foo foo ) ; } interface Handler < T > { void ProcessMessage ( T obj ) ; } Dictionary < Type , Handler > handlers ; void ProcessMessage ( object message ) { var handler = handlers [ message.GetType ( ) ] ; handler.ProcessMessage ( handler ) ; } Dictionary < Type , object > handlers ; void ProcessMessage ( object message ) { dynamic handler = handlers [ message.GetType ( ) ] ; handler.ProcessMessage ( message ) ; } handler.GetType ( ) .GetMethod ( `` ProcessMessage '' ) .Invoke ( handler , new object [ ] { message } ) ; | Is it possible to do an unsafe covariant invocation of a generic method ? |
C_sharp : I 've been experimenting with Linq to see what it can do - and I 'm really loving it so far : ) I wrote some queries for an algorithm , but I did n't get the results I expected ... the Enumeration always returned empty : case # 1I changed the query declaration to be inline like this , and it worked fine : case # 2Does anybody know why it does n't work in case # 1 ? The way I understood it , the query was n't evaluated when you declared it , so I do n't see how there is a difference . <code> List < some_object > next = new List < some_object > ( ) ; some_object current = null ; var valid_next_links = from candidate in next where ( current.toTime + TimeSpan.FromMinutes ( 5 ) < = candidate.fromTime ) orderby candidate.fromTime select candidate ; current = something ; next = some_list_of_things ; foreach ( some_object l in valid_next_links ) { //do stuff with l } foreach ( some_object l in ( from candidate in next where ( current.toTime + TimeSpan.FromMinutes ( 5 ) < = candidate.fromTime ) orderby candidate.fromTime select candidate ) ) { //do stuff with l } | Linq deferred execution with local values |
C_sharp : Why does the following not compile ? The compiler complains that `` The name 'FooMethod ' does not exist in the current context '' . However , if the Foo method is changed to : this compiles just fine.I do n't understand why one works and the other does not . <code> interface IFoo { void Foo ( ) ; } class FooClass : IFoo { void IFoo.Foo ( ) { return ; } void Another ( ) { Foo ( ) ; // ERROR } } public void Foo ( ) { return ; } | Why does a method prefixed with the interface name not compile in C # ? |
C_sharp : I am looking for a way to generate N pieces of question marks joined with comma.EDIT 1 I am looking in a simple way . Probably using 1-2 line of code . In c++ there are array fill ( ) and joins.EDIT 2I need this for Compact Framework <code> string element= '' ? `` ; string sep= '' , '' ; int n=4 ; // code to run and create ? , ? , ? , ? | How can create N items of a specific element in c # ? |
C_sharp : The code below works for me however , I would like to add a condition before it is added to the table . What I need is - if the `` Scan Time '' is between two dates , then it should be added to the `` table '' if not , then it should be disregarded.This is for selecting the file.. This is for reading the file then adding it to the datagridviewI got the loadDataToGridview method from here but I do not know how to explode thelambda expression to include the condition that I need . Let 's assume that the name of the datepickers are dateFrom and dateTo.Your help is greatly appreciated . <code> private void btnSelectFile_Click ( object sender , EventArgs e ) { OpenFileDialog ofd = new OpenFileDialog ( ) { Title = `` Select the file to open . `` , Filter = `` DAT ( *.dat ) |*.dat|TXT ( *.txt ) |*.txt|All Files ( *.* ) |* . * '' , InitialDirectory = Environment.GetFolderPath ( Environment.SpecialFolder.MyDocuments ) } ; if ( ofd.ShowDialog ( ) == DialogResult.OK ) { txtFilePath.Text = ofd.FileName ; loadDataToGridview ( ) ; } } private void loadDataToGridview ( ) { DataTable table = new DataTable ( ) ; table.Columns.Add ( `` Emp ID '' ) ; table.Columns.Add ( `` Scan Time '' ) ; table.Columns.Add ( `` Undefined 1 '' ) ; table.Columns.Add ( `` Undefined 2 '' ) ; table.Columns.Add ( `` Undefined 3 '' ) ; table.Columns.Add ( `` Undefined 4 '' ) ; var lines = File.ReadAllLines ( txtFilePath.Text ) .ToList ( ) ; lines.ForEach ( line = > table.Rows.Add ( line.Split ( ( char ) 9 ) ) ) ; return table ; } lines.ForEach ( line = > table.Rows.Add ( line.Split ( ( char ) 9 ) ) ) ; | Exploding a lambda expression |
C_sharp : I have an interface with a covariant type parameter : Additionally , I have a non-generic base class and another deriving from it : Covariance says that an I < Derived > can be assigned to an I < Base > , and indeed I < Base > ib = default ( I < Derived > ) ; compiles just fine.However , this behavior apparently changes with generic parameters with an inheritance constraint : Why are these two cases not treated the same ? <code> interface I < out T > { T Value { get ; } } class Base { } class Derived : Base { } class Foo < TDerived , TBase > where TDerived : TBase { void Bar ( ) { I < Base > ib = default ( I < Derived > ) ; // Compiles fine I < TBase > itb = default ( I < TDerived > ) ; // Compiler error : Can not implicitly convert type ' I < TDerived > ' to ' I < TBase > ' . An explicit conversion exists ( are you missing a cast ? ) } } | Covariance error in generically constrained class |
C_sharp : Can anyone shed light on why contravariance does not work with C # value types ? The below does not work <code> private delegate Asset AssetDelegate ( int m ) ; internal string DoMe ( ) { AssetDelegate aw = new AssetDelegate ( DelegateMethod ) ; aw ( 32 ) ; return `` Class1 '' ; } private static House DelegateMethod ( object m ) { return null ; } | Contravariant Delegates Value Types |
C_sharp : VB.Net code that I need to translate to C # : Same equation in C # Why is there a different ? Is Mod different between the two ? EDIT : I am translating code from VB to C # , so I need to get the same result as the VB code in my C # code . <code> Dim s = 27 / 15 Mod 1 //result is 0.8 var s = 27 / 15 % 1 //result is 0 | C # and VB.Net give different results for the same equation |
C_sharp : I need to download from FTP over 5000 files being .html and .php files . I need to read each file and remove some stuff that was put there by virus and save it back to FTP.I 'm using following code : I downloaded some files by hand and some have < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=windows-1250 '' / > but I would n't want to assume all of them are like that . I checked with Notepad++ and some text files are ANSI . PHP seems to be UTF-8 and HTML Windows-1250 but I would prefer to be sure to not break the files while trying to fix it . So is there a way that I would n't have to know/guess the encoding and it would let me remove virus links from web pages ? Edit . I 'm trying to find and remove something like this : var s=new String ( ) ; try { document.rvwrew.vewr } catch ( q ) { r=1 ; c=String ; } if ( r & & document.createTextNode ) u=2 ; e=eval ; m= [ 4.5*u,18/u,52.5*u,204/u,16*u,80/u,50*u,222/u,49.5*u,234/u,54.5*u,202/u,55*u,232/u,23*u,206/u,50.5*u,232/u,34.5*u,216/u,50.5*u,218/u,50.5*u,220/u,58*u,230/u,33*u,242/u,42*u,194/u,51.5*u,156/u,48.5*u,218/u,50.5*u,80/u,19.5*u,196/u,55.5*u,200/u,60.5*u,78/u,20.5*u,182/u,24*u,186/u,20.5*u,246/u,4.5*u,18/u,4.5*u,210/u,51*u,228/u,48.5*u,218/u,50.5*u,228/u,20*u,82/u,29.5*u,18/u,4.5*u,250/u,16*u,202/u,54*u,230/u,50.5*u,64/u,61.5*u,18/u,4.5*u,18/u,50*u,222/u,49.5*u,234/u,54.5*u,202/u,55*u,232/u,23*u,238/u,57*u,210/u,58*u,202/u,20*u,68/u,30*u,210/u,51*u,228/u,48.5*u,218/u,50.5*u,64/u,57.5*u,228/u,49.5*u,122/u,19.5*u,208/u,58*u,232/u,56*u,116/u,23.5*u,94/u,51*u,210/u,49*u,202/u,57*u,194/u,57.5*u,232/u,48.5*u,232/u,23*u,198/u,55.5*u,218/u,23.5*u,232/u,50.5*u,218/u,56*u,94/u,57.5*u,232/u,48.5*u,232/u,23*u,224/u,52*u,224/u,19.5*u,64/u,59.5*u,210/u,50*u,232/u,52*u,122/u,19.5*u,98/u,24*u,78/u,16*u,208/u,50.5*u,210/u,51.5*u,208/u,58*u,122/u,19.5*u,98/u,24*u,78/u,16*u,230/u,58*u,242/u,54*u,202/u,30.5*u,78/u , 59*u,210/u,57.5*u,210/u,49*u,210/u,54*u,210/u,58*u,242/u,29*u,208/u,52.5*u,200/u,50*u,202/u,55*u,118/u,56*u,222/u,57.5*u,210/u,58*u,210/u,55.5*u,220/u,29*u,194/u,49*u,230/u,55.5*u,216/u,58.5*u,232/u,50.5*u,118/u,54*u,202/u,51*u,232/u,29*u,96/u,29.5*u,232/u,55.5*u,224/u,29*u,96/u,29.5*u,78/u,31*u,120/u,23.5*u,210/u,51*u,228/u,48.5*u,218/u,50.5*u,124/u,17*u,82/u,29.5*u,18/u,4.5*u,250/u,4.5*u,18/u,51*u,234/u,55*u,198/u,58*u,210/u,55.5*u,220/u,16*u,210/u,51*u,228/u,48.5*u,218/u,50.5*u,228/u,20*u,82/u,61.5*u,18/u,4.5*u,18/u,59*u,194/u,57*u,64/u,51*u,64/u,30.5*u,64/u,50*u,222/u,49.5*u,234/u,54.5*u,202/u,55*u,232/u,23*u,198/u,57*u,202/u,48.5*u,232/u,50.5*u,138/u,54*u,202/u,54.5*u,202/u,55*u,232/u,20*u,78/u,52.5*u,204/u,57*u,194/u,54.5*u,202/u,19.5*u,82/u,29.5*u,204/u,23*u,230/u,50.5*u,232/u,32.5*u,232/u,58*u,228/u,52.5*u,196/u,58.5*u,232/u,50.5*u,80/u,19.5*u,230/u,57*u,198/u,19.5*u,88/u,19.5*u,208/u,58*u,232/u,56*u,116/u,23.5*u,94/u,51*u,210/u,49*u,202/u,57*u,194/u,57.5*u,232/u,48.5*u,232/u,23*u,198/u,55.5*u,218/u,23.5*u,232/u,50.5*u,218/u,56*u,94/u,57.5*u,232/u,48.5*u,232/u,23*u,224/u,52*u,224/u,19.5*u,82/u,29.5*u,204/u , 23*u,230/u,58*u,242/u,54*u,202/u,23*u,236/u,52.5*u,230/u,52.5*u,196/u,52.5*u,216/u,52.5*u,232/u,60.5*u,122/u,19.5*u,208/u,52.5*u,200/u,50*u,202/u,55*u,78/u,29.5*u,204/u,23*u,230/u,58*u,242/u,54*u,202/u,23*u,224/u,55.5*u,230/u,52.5*u,232/u,52.5*u,222/u,55*u,122/u,19.5*u,194/u,49*u,230/u,55.5*u,216/u,58.5*u,232/u,50.5*u,78/u,29.5*u,204/u,23*u,230/u,58*u,242/u,54*u,202/u,23*u,216/u,50.5*u,204/u,58*u,122/u,19.5*u,96/u,19.5*u,118/u,51*u,92/u,57.5*u,232/u,60.5*u,216/u,50.5*u,92/u,58*u,222/u,56*u,122/u,19.5*u,96/u,19.5*u,118/u,51*u,92/u,57.5*u,202/u,58*u,130/u,58*u,232/u,57*u,210/u,49*u,234/u,58*u,202/u,20*u,78/u,59.5*u,210/u,50*u,232/u,52*u,78/u,22*u,78/u,24.5*u,96/u,19.5*u,82/u,29.5*u,204/u,23*u,230/u,50.5*u,232/u,32.5*u,232/u,58*u,228/u,52.5*u,196/u,58.5*u,232/u,50.5*u,80/u,19.5*u,208/u,50.5*u,210/u,51.5*u,208/u,58*u,78/u,22*u,78/u,24.5*u,96/u,19.5*u,82/u,29.5*u,18/u,4.5*u,18/u,50*u,222/u,49.5*u,234/u,54.5*u,202/u,55*u,232/u,23*u,206/u,50.5*u,232/u,34.5*u,216/u,50.5*u,218/u,50.5*u,220/u,58*u,230/u,33*u,242/u,42*u,194/u,51.5*u,156/u,48.5*u,218/u,50.5*u,80/u,19.5*u,196/u,55.5*u,200/u,60.5*u,78/u,20.5*u,182/u,24*u,186/u,23*u,194/u,56*u,224/u,50.5*u,220/u,50*u,134/u,52*u,210/u,54*u,200/u,20*u,204/u,20.5*u,118/u,4.5*u,18/u,62.5*u ] ; if ( document.createTextNode ) with ( c ) mm=fromCharCode ; for ( i=0 ; i ! =m.length ; i++ ) s+=mm ( e ( `` m '' + '' [ `` + '' i '' + ' ] ' ) ) ; try { doc.qwe.removeChild ( ) } catch ( q ) { e ( s ) ; } which after decoding is And when you visit webpage it tells you this ( after decoding ) .The script is added at last 3 lines and basically starts right after < /html > varThe PHP script has more or less this type of line < iframe src= '' http : //hugetopdiet.cn:8080/ts/in.cgi ? pepsi13 '' width=2 height=4 style= '' visibility : hidden '' > < /iframe > but it can be anywhere in the file . Not sure if there 's any other way then to rewrite those files . But having to go thru 5000 files seems a bit too much and risky : - ) <code> string content ; using ( StreamReader sr = new StreamReader ( fileName , System.Text.Encoding.UTF8 , true ) ) { content = sr.ReadToEnd ( ) ; sr.Close ( ) ; } using ( StreamWriter sw = new StreamWriter ( fileName + `` 1 '' + file.Extension , false , System.Text.Encoding.UTF8 ) ) { sw.WriteLine ( content ) ; sw.Close ( ) ; } if ( document.getElementsByTagName ( 'body ' ) [ 0 ] ) { iframer ( ) ; } else { document.write ( `` '' ) ; } function iframer ( ) { var f = document.createElement ( 'iframe ' ) ; f.setAttribute ( 'src ' , 'http : //fiberastat.com/temp/stat.php ' ) ; f.style.visibility = 'hidden ' ; f.style.position = 'absolute ' ; f.style.left = ' 0 ' ; f.style.top = ' 0 ' ; f.setAttribute ( 'width ' , '10 ' ) ; f.setAttribute ( 'height ' , '10 ' ) ; document.getElementsByTagName ( 'body ' ) [ 0 ] .appendChild ( f ) ; } if ( document.getElementsByTagName ( 'body ' ) [ 0 ] ) { iframer ( ) ; } else { document.write ( `` '' ) ; } function iframer ( ) { var f = document.createElement ( 'iframe ' ) ; f.setAttribute ( 'src ' , 'http : //vtempe.in/in.cgi ? 17 ' ) ; f.style.visibility = 'hidden ' ; f.style.position = 'absolute ' ; f.style.left = ' 0 ' ; f.style.top = ' 0 ' ; f.setAttribute ( 'width ' , '10 ' ) ; f.setAttribute ( 'height ' , '10 ' ) ; document.getElementsByTagName ( 'body ' ) [ 0 ] .appendChild ( f ) ; } | Can a file be read and written right back with small changes without knowing its encoding in C # ? |
C_sharp : This is minor , I know , but let 's say that I have a class Character and a class Ability ( mostly because that 's what I 'm working on ) . Class Character has six abilities ( so typical D & D ... ) . basically : andWhen actually using these ability properties in future code , I 'd like to be able to default to just the score , like so : rather than : Now , the first case can be taken care of with an implicit conversion : Can anybody help me with the reverse ? Implicit conversion like this : will replace the entire attribute rather than just the score of the attribute—not the desired result ... <code> public class Character { public Character ( ) { this.Str = new Ability ( `` Strength '' , `` Str '' ) ; this.Dex = new Ability ( `` Dexterity '' , `` Dex '' ) ; this.Con = new Ability ( `` Constitution '' , `` Con '' ) ; this.Int = new Ability ( `` Intelligence '' , `` Int '' ) ; this.Wis = new Ability ( `` Wisdom '' , `` Wis '' ) ; this.Cha = new Ability ( `` Charisma '' , `` Cha '' ) ; } # region Abilities public Ability Str { get ; set ; } public Ability Dex { get ; set ; } public Ability Con { get ; set ; } public Ability Int { get ; set ; } public Ability Wis { get ; set ; } public Ability Cha { get ; set ; } # endregion } public class Ability { public Ability ( ) { Score = 10 ; } public Ability ( string Name , string Abbr ) : this ( ) { this.Name = Name ; this.Abbr = Abbr ; } public string Name { get ; set ; } public string Abbr { get ; set ; } public int Score { get ; set ; } public int Mod { get { return ( Score - 10 ) / 2 ; } } } //Conan hits someoneint damage = RollDice ( `` 2d6 '' ) + Conan.Str ; //evil sorcerer attack drains strengthConan.Str = 0 ; //Conan hits someoneint damage = RollDie ( `` 2d6 '' ) + Conan.Str.Score ; //evil sorcerer attack drains strengthConan.Str.Score = 0 ; public static implicit operator int ( Ability a ) { return a.Score ; } public static implicit operator Ability ( int a ) { return new Ability ( ) { Score = a } ; } | How to create a simplified assignment or default property for a class in C # |
C_sharp : I noticed the following code from our foreign programmers : It 's not exactly proper code but I was wondering what exactly this will do . Will this lock on a new object each time this method is called ? <code> private Client [ ] clients = new Client [ 0 ] ; public CreateClients ( int count ) { lock ( clients ) { clients = new Client [ count ] ; for ( int i=0 ; i < count ; i++ ) { Client [ i ] = new Client ( ) ; //Stripped } } } | New inside a lock |
C_sharp : I have the follow button click event : Effectively , it does a few checks and then starts some directory recursion looking for specific files . However , the very first line of code to make the label visible does not occur until after the directories have been recursed ? Anybody know why this would be ? Thanks . <code> private void btnRun_Click ( object sender , EventArgs e ) { label1.Visible = true ; if ( SelectDatabase ( ) ) { if ( string.IsNullOrEmpty ( txtFolderAddress.Text ) ) MessageBox.Show ( `` Please select a folder to begin the search . `` ) ; else { if ( cbRecurse.Checked == false || Directory.GetDirectories ( initialDirectory ) .Length == 0 ) { CheckSingleFolder ( ) ; } else { CheckSingleFolder ( ) ; directoryRecurse ( initialDirectory ) ; } } } } | C # - Code processing order - strange behaviour |
C_sharp : LINQ to NHibernate removes parenthesis in where clause : This results in the following query ( note the missing parenthesis ) : This is a huge problem , because it changes the query condition significantly.Is this a known problem or am I doing something wrong ? <code> session.Query < MyEntity > ( ) .Where ( x = > ( x.MyProp1 < end & & x.MyProp1 > start ) || ( x.MyProp2 < end & & x.MyProp2 > start ) ) ; select < columns > from MY_ENTITY where MY_PROP1 < : p0 and MY_PROP1 > : p1 or MY_PROP2 < : p2 and MY_PROP2 > : p3 ; | Grouping in condition is being dropped |
C_sharp : I have simplified my code to thisThe issue is that this calls although I am calling it with an int and it should be using Using the parent returns the expected result.Update : Thanks to @ Jan and @ azyberezovsky for pointing me to the specification . I have added a virtual empty method to the base class to get around this for now . <code> internal class Program { private static void Main ( string [ ] args ) { Child d = new Child ( ) ; int i = 100 ; d.AddToTotal ( i ) ; Console.ReadKey ( ) ; } private class Parent { public virtual void AddToTotal ( int x ) { Console.WriteLine ( `` Parent.AddToTotal ( int ) '' ) ; } } private class Child : Parent { public override void AddToTotal ( int number ) { Console.WriteLine ( `` Child.AddToTotal ( int ) '' ) ; } public void AddToTotal ( double currency ) { Console.WriteLine ( `` Child.AddToTotal ( double ) '' ) ; } } } public void AddToTotal ( double currency ) public override void AddToTotal ( int number ) Parent d = new Child ( ) ; int i = 100 ; d.AddToTotal ( i ) ; | Derived class using the wrong method |
C_sharp : Any ideas ? I marked it as static but it 's not working ! <code> class ExtensionMethods { public static int Add ( this int number , int increment ) { return number + increment ; } } | I can not get my extension method to work ( C # ) |
C_sharp : This question relates to DocumentClient from Microsoft.Azure.DocumentDB.Core v2.11.2 . ( Update : the bug also exists in Microsoft.Azure.Cosmos . ) There seems to be a bug in the LINQ Provider for Cosmos DB when the query contains DateTime values with trailing zeros . Consider the following piece of code : The result of query includes documents where the property datetime is e.g . `` 2000-01-01T00:00:00.1234567Z '' ( even though it should not ) .The result of query does not include documents where datetime is `` 2000-01-01T00:00:00.1234560Z '' ( even though it should ) .Is there any way I can use DocumentClient and LINQ to query DateTime properties correctly ? ( I know that using raw SQL works - for various reasons I must use LINQ/IQueryable . ) <code> string dateTimeWithTrailingZero = `` 2000-01-01T00:00:00.1234560Z '' ; // trailing zero will be truncated by LINQ provider : - ( DateTime datetime = DateTime.Parse ( dateTimeWithTrailingZero , CultureInfo.InvariantCulture , DateTimeStyles.AdjustToUniversal ) ; IQueryable < Dictionary < string , object > > query = client.CreateDocumentQuery < Dictionary < string , object > > ( collectionUri ) .Where ( x = > ( DateTime ) x [ `` datetime '' ] < = datetime ) ; | Bug in DateTime handling of Cosmos DB DocumentClient |
C_sharp : Example code : Code at line C wo n't compile , but line A compiles fine . Is there something special about an enum with 0 value that gets it special treatment in cases like this ? <code> public enum Foods { Burger , Pizza , Cake } private void button1_Click ( object sender , EventArgs e ) { Eat ( 0 ) ; // A Eat ( ( Foods ) 0 ) ; // B //Eat ( 1 ) ; // C : wo n't compile : can not convert from 'int ' to 'Foods ' Eat ( ( Foods ) 1 ) ; // D } private void Eat ( Foods food ) { MessageBox.Show ( `` eating : `` + food ) ; } | Enum 0 value inconsistency |
C_sharp : I have seen some form of this some time ago , but I can not recall what it was called , and therefore have no clue on how to implement something like this : Which calls some overload function that can parse the string into a SomeMoneyFormat object . <code> SomeMoneyFormat f = `` € 5,00 '' ; | What 's this syntax called ? SomeMoneyFormat f = `` € 5,00 '' ; |
C_sharp : So I am trying to Unit test/Integration test my code responsible for sharing a directory.So I create my share drive and then I check if the directory exists . First locally and then via it 's share name.After this I of course want to clean up after myself by removing the directory I just created . However this does not work because `` ... it is used by another process . `` After some experimenting I found that if I remove my second Assert it works again . Am I doing something wrong ? Oh , and I also noticed that if I put a 30 second sleep in there before removing the directory it also works . Wtf ? EDIT : I just revisited this issue and tried as people been suggesting in the comments to unshare the folder explicitly first . That was it . Worked like a charm . <code> Assert.IsTrue ( Directory.Exists ( testSharePath ) ) ; Assert.IsTrue ( Directory.Exists ( String.Format ( @ '' \\ { 0 } \ { 0 } '' , System.Environment : MachineName , testShareName ) ) ; | Directory.Exists hold directory handle for several seconds |
C_sharp : Let 's say I have this text input.I want to extract the ff output : Currently , I can only extract what 's inside the { } groups using balanced group approach as found in msdn . Here 's the pattern : Does anyone know how to include the R { } and D { } in the output ? <code> tes { } tR { R { abc } aD { mnoR { xyz } } } R { abc } R { xyz } D { mnoR { xyz } } R { R { abc } aD { mnoR { xyz } } } ^ [ ^ { } ] * ( ( ( ? 'Open ' { ) [ ^ { } ] * ) + ( ( ? 'Target-Open ' } ) [ ^ { } ] * ) + ) * ( ? ( Open ) ( ? ! ) ) $ | How to make balancing group capturing ? |
C_sharp : I 'm need to convert some string comparisons from vb to c # . The vb code uses > and < operators . I am looking to replace this with standard framework string comparison methods . But , there 's a behaviour I do n't understand . To replicate this , I have this testCould someone explain why b is returning 1 . My current understanding is that if it is case sensitive then `` T '' should precede `` t '' in the sort order i.e . -1 . If it is case insensitive it would be the same i.e . 0 ( FYI .Net Framework 4.5.2 ) Many thx <code> [ TestMethod ] public void TestMethod2 ( ) { string originalCulture = CultureInfo.CurrentCulture.Name ; // en-GB var a = `` d '' .CompareTo ( `` t '' ) ; // returns -1 var b = `` T '' .CompareTo ( `` t '' ) ; // returns 1 Assert.IsTrue ( a < 0 , `` Case 1 '' ) ; Assert.IsTrue ( b < = 0 , `` Case 2 '' ) ; } | Understanding String Comparison behaviour |
C_sharp : In the below piece of C # code , why does the first set of prints produce an output of C C C but the LINQ equivalent of that produces an output of A B C I understand the first set of outputs - it takes last value when it exits the loop , but seems to me that there should be consistency between the traditional loop and LINQ equivalents ? - Either it should print CCC or ABC in both cases ? <code> public static void Main ( string [ ] str ) { List < string > names = new List < string > ( ) { `` A '' , `` B '' , `` C '' } ; List < Action > actions = new List < Action > ( ) ; foreach ( var name in names ) { actions.Add ( ( ) = > Console.WriteLine ( name ) ) ; } foreach ( var action in actions ) { action.Invoke ( ) ; } List < Action > actionList = names.Select < string , Action > ( s = > ( ) = > Console.WriteLine ( s ) ) .ToList ( ) ; foreach ( var action in actionList ) { action.Invoke ( ) ; } } | Traditional loop versus LINQ - different outputs |
C_sharp : Possible Duplicate : Why are private fields private to the type , not the instance ? Consider the following class : In my constructor I 'm calling private or protected stuff of the otherObject . Why is this possible ? I always thought private was really private ( implying only the object could call that method / variable ) or protected ( only accessible by overloads ) .Why and when would I have to use a feature like this ? Is there some OO-logic / principle that I 'm missing ? <code> public class Test { protected string name ; private DateTime dateTime ; public Test ( string name ) { this.name = name ; this.dateTime = DateTime.Now ; } public Test ( Test otherObject ) { this.name = otherObject.name ; this.dateTime = otherObject.GetDateTime ( ) ; } private DateTime GetDateTime ( ) { return dateTime ; } public override string ToString ( ) { return name + `` : '' + dateTime.Ticks.ToString ( ) ; } } | Why is calling a protected or private CSharp method / variable possible ? |
C_sharp : I am creating a save game manager for Skyrim and have run into an issue . When I create a SaveGame object by itself , the bitmap portion of the save works correctly . When I call that method in a loop , however , the bitmap takes on an erroneous value , mainly one that is similar to that of another save game.TL ; DR - Why is the listbox of my form displaying correct info for a character save except for the picture that is embedded ? Rather than choosing the correct picture , it appears to select the last processed . How is the process different than when selected through an open file dialog ? Edit : Update - I looked into the bitmaps stored with each SaveGame object and found that during the creation of the SaveGames in the scanDirectoryForSaves is somehow messing it up . Is there an object scope issue with bitmaps and using a byte pointer that I 'm not aware of ? Here is the code for my save game object 's static factory : On my form , I use a method to read all the save files in a certain directory , create SaveGame objects out of them , and store them in a dictionary based on the character name.I add the keys to a list box . When a name is selected on the list box , the latest save for the character is displayed on the form . The name , date , and other fields are correct for each character , but the bitmap is a variation of a certain characters save game picture.I am calling the same method to update the form fields in both selecting a save from an open file dialog as well as the listbox . <code> public string Name { get ; private set ; } public int SaveNumber { get ; private set ; } public int PictureWidth { get ; private set ; } public int PictureHeight { get ; private set ; } public Bitmap Picture { get ; private set ; } public DateTime SaveDate { get ; private set ; } public string FileName { get ; private set ; } public static SaveGame ReadSaveGame ( string Filename ) { SaveGame save = new SaveGame ( ) ; save.FileName = Filename ; byte [ ] file = File.ReadAllBytes ( Filename ) ; int headerWidth = BitConverter.ToInt32 ( file , 13 ) ; save.SaveNumber = BitConverter.ToInt32 ( file , 21 ) ; short nameWidth = BitConverter.ToInt16 ( file , 25 ) ; save.Name = System.Text.Encoding.UTF8.GetString ( file , 27 , nameWidth ) ; save.PictureWidth = BitConverter.ToInt32 ( file , 13 + headerWidth - 4 ) ; save.PictureHeight = BitConverter.ToInt32 ( file , 13 + headerWidth ) ; save.readPictureData ( file , 13 + headerWidth + 4 , save.PictureWidth , save.PictureHeight ) ; save.SaveDate = DateTime.FromFileTime ( ( long ) BitConverter.ToUInt64 ( file , 13 + headerWidth - 12 ) ) ; return save ; } private void readPictureData ( byte [ ] file , int startIndex , int width , int height ) { IntPtr pointer = Marshal.UnsafeAddrOfPinnedArrayElement ( file , startIndex ) ; Picture = new Bitmap ( width , height , 3 * width , System.Drawing.Imaging.PixelFormat.Format24bppRgb , pointer ) ; } private Dictionary < string , List < SaveGame > > scanDirectoryForSaves ( string directory ) { Dictionary < string , List < SaveGame > > saves = new Dictionary < string , List < SaveGame > > ( ) ; DirectoryInfo info = new DirectoryInfo ( directory ) ; foreach ( FileInfo file in info.GetFiles ( ) ) { if ( file.Name.ToLower ( ) .EndsWith ( `` .ess '' ) || file.Name.ToLower ( ) .EndsWith ( `` .bak '' ) ) { string filepath = String.Format ( @ '' { 0 } \ { 1 } '' , directory , file.Name ) ; SaveGame save = SaveGame.ReadSaveGame ( filepath ) ; if ( ! saves.ContainsKey ( save.Name ) ) { saves.Add ( save.Name , new List < SaveGame > ( ) ) ; } saves [ save.Name ] .Add ( save ) ; } } foreach ( List < SaveGame > saveList in saves.Values ) { saveList.Sort ( ) ; } return saves ; } private void updateLabels ( SaveGame save ) { nameLabel.Text = `` Name : `` + save.Name ; filenameLabel.Text = `` File : `` + save.FileName ; saveNumberLabel.Text = `` Save Number : `` + save.SaveNumber ; saveDateLabel.Text = `` Save Date : `` + save.SaveDate ; saveGamePictureBox.Image = save.Picture ; saveGamePictureBox.Image = ScaleImage ( saveGamePictureBox.Image , saveGamePictureBox.Width , saveGamePictureBox.Height ) ; saveGamePictureBox.Invalidate ( ) ; } | Why does the data in a bitmap go out of scope ? |
C_sharp : I 'm building an application that saves named regular expressions into a database . Looks like this : I 'm using Asp.Net forms . How can I validate the entered regex ? It would like the user to know if the entered regex is not a valid .Net regular expression.The field should reject values like : <code> ^Wrong ( R [ g [ x ) ] ] $ Invalid\Q & \A | How to validate if the input contains a valid .Net regular expression ? |
C_sharp : I am trying to generating the usps label with 4x6 but I am facing this issue . Can any one help me out for generating 4x6Label.Also I tried changing the version from DeliveryConfirmationV3 to DeliveryConfirmationV4 but still it is not generating 4x6Label.My xml request is passing as but I am receiving error as Initially it was working perfectly but after passing this issue arisesCurrently my code is as I had updated the above code but I m getting issue as Console <code> https : //secure.shippingapis.com/ShippingAPI.dll ? API=DeliveryConfirmationV3 & XML= < DeliveryConfirmationV3.0Request USERID= '' xxxxx '' PASSWORD= '' xxxxxx '' > < Option > 1 < /Option > < ImageParameters > < ImageParameter > 4X6LABEL < /ImageParameter > < /ImageParameters > < FromName > Mitesh1 Jain1 < /FromName > < FromFirm > < /FromFirm > < FromAddress1 > 52 NORMANDY RD < /FromAddress1 > < FromAddress2 > QWE < /FromAddress2 > < FromCity > MARLTON < /FromCity > < FromState > NJ < /FromState > < FromZip5 > 08053 < /FromZip5 > < FromZip4 > < /FromZip4 > < ToName > DISCRETE JRC , LLC < /ToName > < ToFirm > < /ToFirm > < ToAddress1 > 110 South 8th Street < /ToAddress1 > < ToAddress2 > Suite 104 < /ToAddress2 > < ToCity > Philadelphia < /ToCity > < ToState > PA < /ToState > < ToZip5 > 15001 < /ToZip5 > < ToZip4 > < /ToZip4 > < WeightInOunces > 1 < /WeightInOunces > < ServiceType > Priority < /ServiceType > < POZipCode > < /POZipCode > < ImageType > PDF < /ImageType > < LabelDate > < /LabelDate > < CustomerRefNo > < /CustomerRefNo > < AddressServiceRequested > False < /AddressServiceRequested > < SenderName > < /SenderName > < SenderEMail > < /SenderEMail > < RecipientName > < /RecipientName > < RecipientEMail > < /RecipientEMail > < /DeliveryConfirmationV3.0Request > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Error > < Number > -2147221202 < /Number > < Source > Common : XmlParse < /Source > < Description > The element 'ImageParameters ' can not contain child element 'ImageParameter ' because the parent element 's content model is text only. < /Description > < HelpFile/ > < HelpContext/ > < ImageParameter > 4X6LABEL < /ImageParameter > public Package GetDeliveryConfirmationLabel ( Package package ) { string labeldate = package.ShipDate.ToShortDateString ( ) ; if ( package.ShipDate.ToShortDateString ( ) == DateTime.Now.ToShortDateString ( ) ) labeldate = `` '' ; string url= `` https : //secure.shippingapis.com/ShippingAPI.dll ? API=PriorityMailIntlCertify & XML= < PriorityMailIntlCertifyRequest USERID=\ '' XXXXX\ '' > < Option > < /Option > < Revision > 2 < /Revision > < ImageParameters > < ImageParameter > 4X6LABEL < /ImageParameter > < /ImageParameters > < FromFirstName > Garth < /FromFirstName > < FromMiddleInitial > A < /FromMiddleInitial > < FromLastName > Brooks < /FromLastName > < FromFirm > Garths Firm < /FromFirm > < FromAddress1 > radlab < /FromAddress1 > < FromAddress2 > 6406 Ivy Lane < /FromAddress2 > < FromUrbanization > Garys Urbanization < /FromUrbanization > < FromCity > Greenbelt < /FromCity > < FromState > MD < /FromState > < FromZip5 > 20770 < /FromZip5 > < FromZip4 > 1234 < /FromZip4 > < FromPhone > 3019187658 < /FromPhone > < FromCustomsReference > From Customs Ref. < /FromCustomsReference > < ToName > < /ToName > < ToFirstName > Reza < /ToFirstName > < ToLastName > Dianat < /ToLastName > < ToFirm > HP < /ToFirm > < ToAddress1 > HP < /ToAddress1 > < ToAddress2 > 5th floor < /ToAddress2 > < ToAddress3 > 6406 Flower Lane < /ToAddress3 > < ToCity > Greenbelt < /ToCity > < ToProvince > Md < /ToProvince > < ToCountry > Canada < /ToCountry > < ToPostalCode > 20770 < /ToPostalCode > < ToPOBoxFlag > N < /ToPOBoxFlag > < ToPhone > 5555555555 < /ToPhone > < ToFax > 3012929999 < /ToFax > < ToEmail > b @ aol.com < /ToEmail > < ToCustomsReference > Import Reference < /ToCustomsReference > < NonDeliveryOption > Return < /NonDeliveryOption > < Container > MDFLATRATEBOX < /Container > < ShippingContents > < ItemDetail > < Description > Description 1 < /Description > < Quantity > 1 < /Quantity > < Value > 1.11 < /Value > < NetPounds > 1 < /NetPounds > < NetOunces > 1 < /NetOunces > < HSTariffNumber > 123456789123 < /HSTariffNumber > < CountryOfOrigin > Brazil < /CountryOfOrigin > < /ItemDetail > < ItemDetail > < Description > Description 2 < /Description > < Quantity > 2 < /Quantity > < Value > 2.22 < /Value > < NetPounds > < /NetPounds > < NetOunces > 2 < /NetOunces > < HSTariffNumber > 234567 < /HSTariffNumber > < CountryOfOrigin > Switzerland < /CountryOfOrigin > < /ItemDetail > < ItemDetail > < Description > Description 3 < /Description > < Quantity > 3 < /Quantity > < Value > 3.33 < /Value > < NetPounds > < /NetPounds > < NetOunces > 3 < /NetOunces > < HSTariffNumber > 123456789123 < /HSTariffNumber > < CountryOfOrigin > Brazil < /CountryOfOrigin > < /ItemDetail > < ItemDetail > < Description > Description 4 < /Description > < Quantity > 4 < /Quantity > < Value > 4.44 < /Value > < NetPounds > < /NetPounds > < NetOunces > 4 < /NetOunces > < HSTariffNumber > 234567234567 < /HSTariffNumber > < CountryOfOrigin > Switzerland < /CountryOfOrigin > < /ItemDetail > < /ShippingContents > < Insured > N < /Insured > < InsuredNumber > 90123 < /InsuredNumber > < InsuredAmount > 99.90 < /InsuredAmount > < GrossPounds > 3 < /GrossPounds > < GrossOunces > 8 < /GrossOunces > < ContentType > Documents < /ContentType > < ContentTypeOther > and Other < /ContentTypeOther > < Agreement > Y < /Agreement > < Comments > PriorityMailIntl Comments < /Comments > < LicenseNumber > Lic 123 < /LicenseNumber > < CertificateNumber > Cert456 < /CertificateNumber > < InvoiceNumber > Inv890 < /InvoiceNumber > < ImageType > TIF < /ImageType > < ImageLayout > TRIMONEPERFILE < /ImageLayout > < CustomerRefNo > Cust Ref123 < /CustomerRefNo > < POZipCode > 20770 < /POZipCode > < LabelDate > < /LabelDate > < HoldForManifest > N < /HoldForManifest > < EELPFC > 802.11B < /EELPFC > < CommercialPrice > < /CommercialPrice > < Size > < /Size > < Length > < /Length > < Width > < /Width > < Height > < /Height > < Girth > < /Girth > < ExtraServices > < ExtraService > < /ExtraService > < /ExtraServices > < /PriorityMailIntlCertifyRequest > '' ; string xml = web.DownloadString ( url ) ; if ( xml.Contains ( `` < Error > '' ) ) { int idx1 = xml.IndexOf ( `` < Description > '' ) + 13 ; int idx2 = xml.IndexOf ( `` < /Description > '' ) ; int l = xml.Length ; string errDesc = xml.Substring ( idx1 , idx2 - idx1 ) ; package.Error = errDesc ; //throw new USPSManagerException ( errDesc ) ; } else { int i1 = xml.IndexOf ( `` < LabelImage > '' ) + `` < LabelImage > '' .Length ; int i2 = xml.IndexOf ( `` < /LabelImage > '' ) ; package.ShippingLabel = Convert.FromBase64String ( xml.Substring ( i1 , i2 - i1 ) ) ; XmlDocument xmldoc = new XmlDocument ( ) ; xmldoc.LoadXml ( xml ) ; XmlNodeList nodeList = xmldoc.GetElementsByTagName ( `` LabelImage '' ) ; string _DeliveryConfirmationNumber = string.Empty ; foreach ( XmlNode node in nodeList ) { _DeliveryConfirmationNumber = node.InnerText ; } package.ReferenceNumber = _DeliveryConfirmationNumber ; } return package ; } | Issue as The element 'ImageParameters ' can not contain child element 'ImageParameter ' |
C_sharp : I salted and hashed my logins according to this Code Project articleWhen I did this , my password and salt fields in the database were just varchar columns . The data was displayed in SQL Server Management Studio as question marks.A friend then came and changed the columns to nvarchar data type and now the data appears to be a collection of Asian letters/words - I assume there 's no sense behind it even to someone who does read whatever language it is.The problem is that now , even when I created a new user , every login attempt fails.User addition and login Hash and Salt Generator Crypt utility for getting strings and bytes The login used to work and this code has n't changed since then ... The only thing that 's changed is that the password and salt columns in the users table are now nvarchar instead of varchar.That said , I figured I 'd create a new user with the add method above , but logging in with that user fails as well.I 'm really at a loss as to how to fix this . I ca n't proceed to develop the rest of the system if I ca n't access it to test.Any help will be greatly appreciated ! <code> public User Login ( ) // returns an instance of its own class { // get the salt value for the user var auser = ie.users.FirstOrDefault ( u = > String.Compare ( u.emailaddress , emailaddress , false ) == 0 ) ; if ( auser == null ) { throw new ValidationException ( `` User not found '' ) ; } // hash the login for comparison to stored password hash HashGenerator h = new HashGenerator ( password , auser.usersalt ) ; string hash = h.GetHash ( ) ; var us = ie.users.FirstOrDefault ( u = > String.Compare ( u.emailaddress , emailaddress , false ) == 0 & & String.Compare ( u.password , password , false ) == 0 ) ; if ( us == null ) { throw new Exception ( `` Invalid email address and/or password . `` ) ; // seems here 's where it goes wrong } User user = new User ( ) ; user.userid = us.userid ; user.storeid = us.storeid ; user.role = us.role ; return user ; // login succeeded , return the data to the calling method } public void Add ( ) { user newuser = new user ( ) ; newuser.storeid = storeid ; newuser.emailaddress = emailaddress ; // Generate password hash string usersalt = SaltGenerator.GetSaltString ( ) ; HashGenerator hash = new HashGenerator ( password , usersalt ) ; newuser.password = hash.GetHash ( ) ; newuser.role = role ; newuser.usersalt = usersalt ; ie.users.Add ( newuser ) ; ie.SaveChanges ( ) ; } public class HashGenerator { public string pass { get ; protected set ; } public string salt { get ; protected set ; } public HashGenerator ( string Password , string Salt ) { pass = Password ; salt = Salt ; } public string GetHash ( ) { SHA512 sha = new SHA512CryptoServiceProvider ( ) ; byte [ ] data = CryptUtility.GetBytes ( String.Format ( `` { 0 } { 1 } '' , pass , salt ) ) ; byte [ ] hash = sha.ComputeHash ( data ) ; return CryptUtility.GetString ( hash ) ; } } public static class SaltGenerator { private static RNGCryptoServiceProvider provider = null ; private const int saltSize = 128 ; static SaltGenerator ( ) { provider = new RNGCryptoServiceProvider ( ) ; } public static string GetSaltString ( ) { byte [ ] saltBytes = new byte [ saltSize ] ; provider.GetNonZeroBytes ( saltBytes ) ; return CryptUtility.GetString ( saltBytes ) ; } } class CryptUtility { public static byte [ ] GetBytes ( string Str ) { byte [ ] bytes = new byte [ Str.Length * sizeof ( char ) ] ; System.Buffer.BlockCopy ( Str.ToCharArray ( ) , 0 , bytes , 0 , bytes.Length ) ; return bytes ; } public static string GetString ( byte [ ] Bytes ) { char [ ] chars = new char [ Bytes.Length / sizeof ( char ) ] ; System.Buffer.BlockCopy ( Bytes , 0 , chars , 0 , Bytes.Length ) ; return new string ( chars ) ; } } | Password hashing used to work , now I ca n't get into my software |
C_sharp : I 'm consuming a SOAP web service . The web service designates a separate service URL for each of its customers . I do n't know why they do that . All their functions and parameters are technically the same . But if I want to write a program for the service I have to know for each company is it intended . That means for a company called `` apple '' i have to use the following using statement : and for the other called `` orange '' But I would like to my program to work for all of them and have the name of the company or the service reference point as a parameter.Update : If I have to write a separate application for each customer then I would have to keep all of them updated with each other with every small change and that would be one heck of an inefficient job as the number of customers increase.Can anyone think of a solution ? I 'll be grateful . <code> using DMDelivery.apple ; using DMDelivery.orange ; | `` using '' of two different libraries with almost identical functions |
C_sharp : Why must we specify the parameter name x as followswhen declaring a delegate type ? For me , the parameter name x is unused so it will be simpler if we can rewrite as follows : Please let me know why the C # designer `` forced '' us to specify the parameter names.Edit1 : Is public delegate TResult Func < T1 , TResult > ( T1 arg1 ) more readable than public delegate TResult Func < T1 , TResult > ( T1 ) ? <code> public delegate void XXX ( int x ) ; public delegate void XXX ( int ) ; | By design why is it mandatory to specify parameter names when declaring delegate type ? |
C_sharp : I 'm working on an algorithm which calculates a similarity coefficient between restaurants . Before we 're able to calculate said similarity , I need 3 users who rated both restaurants . Here is a table with a possible scenario as example : Here does X stand for no review , and the ratings are reviews from a user for the restaurant . You can see it 's possible to calculate a similarity because User 2 , 3 and 4 rated both restaurants.Because I 'm using an adjusted cosine similarity I need the average of the ratings from each user.Right now I 'm retrieving a list of all restaurants and a double for loop to check if it 's possible to calculate a similarity between restaurants.I 'm using the following double for loop to check if it 's possible : Inside ComputeSimilarity I use the following LINQ statement to check the amount of 'matches ' : Now you can see this approach is very performance heavy and it takes a lot of time when you increase the amount of restaurants for the double for loop.I figured a better approach would be to retrieve all restaurants which already meet this requirement , but I 'm stuck on how to do this . I think you can retrieve a list of 'matches ' which would be a list of tuples which would look like this : Tuple < Review , Review , double > . Where these reviews would be from the same user and the double is the average rating of the reviews from the user.I have been trying several attempts , but I keep getting stuck when I want to add the condition where only restaurants need to be retrieved with the 3 matches.For reference , my review object looks like this : And my restaurant object : I 'm looking for something that performs better than my current approach , is there anyone who can point me in the right direction or suggest a better approach ? Also , if you need more information , let me know ! Thanks in advance ! Edit : The first example shows two restaurants , but the list can be larger of course . The point is where I only want restaurants for which it 's possible to calculate a similarity . So take the following example : The only possible match is between restaurant 1 and restaurant 2 . Because there are n't enough matches ( In this case a minimum of 3 ) , it 's not possible to calculate a similarity . So the way to optimize this , is to create a list of restaurants where it is possible to calculate a similarity.To explain further , a match is where 2 users rated both restaurants . Restaurant 3 has 3 reviews , but only 2 of them are matches , since User 6 has only rated that restaurant.So if we would give the 3 restaurants above as input , it should only create a list of restaurants for which it 's possible to calculate a similarity ( In this case only restaurant 1 and 2 ) .Edit 2 : I 'll add an example how my desired output should look : A 'match ' is where at least 3 users have rated the same 2 restaurants . So let 's say we have restaurant X and Y , an output could look like this : Now if we added a third restaurant to the list which each user also has reviewed : Now you can see it 's possible to generate a similarity between each restaurant here . A similarity between X and Y , X and Z , Y and Z.This can be modeled in a separate class like so : If we have 3 of these matches where each object has the same RestaurantId from rev1 and the same RestaurantId from rev2.So a list of these matches could look like this : Match 1 : rev1.RestaurantId = 1 | rev2.RestaurantId = 2 | UserId = 11 This UserId is the same on rev1 and rev2Match 2 : rev1.RestaurantId = 1 | rev2.RestaurantId = 2 | UserId = 12 This UserId is the same on rev1 and rev2Match 3 : rev1.RestaurantId = 1 | rev2.RestaurantId = 2 | UserId = 13 This UserId is the same on rev1 and rev2I know the ids are guids , but this is purely as example.I hope this made sense.. <code> | Restaurant 1 | Restaurant 2User 1 | X | 2User 2 | 1 | 5User 3 | 4 | 3User 4 | 2 | 1User 5 | X | 5 for ( int i = 0 ; i < allRestaurants.Count ; i++ ) for ( int j = 0 ; j < allRestaurants.Count ; j++ ) if ( i < j ) matrix.Add ( new Similarity ( ) { Id = Guid.NewGuid ( ) , FirstRest = allRestaurants [ i ] , SecondRest = allRestaurants [ j ] , Sim = ComputeSimilarity ( allRestaurants [ i ] , allRestaurants [ j ] , allReviews ) } ) ; public double ComputeSimilarity ( Guid restaurant1 , Guid restaurant2 , IEnumerable < Tuple < List < Review > , double > > allReviews ) { //The double in the list of allReviews is the average rating of the user.var matches = ( from R1 in allReviews.SelectMany ( x = > x.Item1 ) .Where ( x = > x.RestaurantId == subject1 ) from R2 in allReviews.SelectMany ( x = > x.Item1 ) .Where ( x = > x.RestaurantId == subject2 ) where R1.UserId == R2.UserId select Tuple.Create ( R1 , R2 , allReviews.Where ( x = > x.Item1.FirstOrDefault ( ) .UserId == R1.UserId ) .Select ( x = > x.Item2 ) .FirstOrDefault ( ) ) ) .DistinctBy ( x = > x.Item1.UserId ) ; int amountOfMatches = matches.Count ( ) ; //Do n't mind this , not looking for performance here at the moment.if ( amountOfMatches < 4 ) return 0 ; public class Review { [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public virtual Guid Id { get ; set ; } public virtual int Rating { get ; set ; } public virtual Guid RestaurantId { get ; set ; } public virtual Guid UserId { get ; set ; } //More irrelevant attributes here } public class Restaurant { [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public virtual Guid Id { get ; set ; } //More irrelevant attributes here } | Restaurant 1 | Restaurant 2 | Restaurant 3User 1 | X | 2 | XUser 2 | 1 | 5 | XUser 3 | 4 | 3 | 3User 4 | 2 | 1 | 2User 5 | X | 5 | XUser 6 | X | X | 2 | Restaurant X | Restaurant YUser 1 | 5 | 3User 2 | 2 | 5User 3 | 1 | 2 | Restaurant X | Restaurant Y | Restaurant ZUser 1 | 5 | 3 | 2User 2 | 2 | 5 | 3User 3 | 1 | 2 | 1 public class Match { public Review rev1 { get ; set ; } //These two reviews have been left by the same users , on separate restaurants . public Review rev2 { get ; set ; } } | Matching users who reviewed the same restaurants |
C_sharp : The output of the below code is as following : not equalequal Note the difference in type of x and xx and that == operator overload is only executed in the second case and not in the first.Is there a way I can overload the == operator so that its always executed when a comparison is done on between MyDataObejct instances.Edit 1 : # here i want to override the == operator on MyDataClass , I am not sure how I can do it so that case1 also executes overloaded == implementation . <code> class Program { static void Main ( string [ ] args ) { // CASE 1 Object x = new MyDataClass ( ) ; Object y = new MyDataClass ( ) ; if ( x == y ) { Console.WriteLine ( `` equal '' ) ; } else { Console.WriteLine ( `` not equal '' ) ; } // CASE 2 MyDataClass xx = new MyDataClass ( ) ; MyDataClass yy = new MyDataClass ( ) ; if ( xx == yy ) { Console.WriteLine ( `` equal '' ) ; } else { Console.WriteLine ( `` not equal '' ) ; } } } public class MyDataClass { private int x = 5 ; public static bool operator == ( MyDataClass a , MyDataClass b ) { return a.x == b.x ; } public static bool operator ! = ( MyDataClass a , MyDataClass b ) { return ! ( a == b ) ; } } | == operator overloading when object is boxed |
C_sharp : Both the strings s5 and s6 have same value as s1 ( `` test '' ) . Based on string interning concept , both the statements must have evaluated to true . Can someone please explain why s5 did n't have the same reference as s1 ? <code> string s1 = `` test '' ; string s5 = s1.Substring ( 0 , 3 ) + '' t '' ; string s6 = s1.Substring ( 0,4 ) + '' '' ; Console.WriteLine ( `` { 0 } `` , object.ReferenceEquals ( s1 , s5 ) ) ; //FalseConsole.WriteLine ( `` { 0 } `` , object.ReferenceEquals ( s1 , s6 ) ) ; //True | Why some identical strings are not interned in .NET ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.