lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | In the sample code below I get the following exception when doing db.Entry ( a ) .Collection ( x = > x.S ) .IsModified = true : System.InvalidOperationException : 'The instance of entity type ' B ' can not be tracked because another instance with the key value ' { Id : 0 } ' is already being tracked . When attaching ex... | using Microsoft.EntityFrameworkCore ; using Microsoft.Extensions.Logging ; using System ; using System.Collections.Generic ; using System.Linq ; class Program { public class A { public int Id { get ; set ; } public ICollection < B > S { get ; set ; } = new List < B > ( ) { new B { } , new B { } } ; } public class B { p... | Unexpected InvalidOperationException when trying to change relationship via property default value |
C# | I found in legacy code following line : What does [ , ] mean here ? | protected bool [ , ] PixelsChecked ; | bool [ , ] - What does this syntax mean in c # ? |
C# | Is there a generally-accepted best practice for creating an event handler that unsubscribes itself ? E.g. , the first thing I came up with is something like : To say that this feels hackish/bad is an understatement . It 's tightly coupled with a temporal dependency ( HandlerToUnsubscribe must be assigned the exact valu... | // Foo.cs// ... Bar bar = new Bar ( /* add ' l req 'd state */ ) ; EventHandler handler = new EventHandler ( bar.HandlerMethod ) ; bar.HandlerToUnsubscribe = handler ; eventSource.EventName += handler ; // ... // Bar.csclass Bar { /* add ' l req 'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get ; set ... | Am I using the right approach to monitor the tasks I want to perform when a handle is created ? |
C# | The `` using '' construct looks incredibly handy for situations that require both beginning and separated end parts . Quick example to illustrate : The beginning part is defined as the constructor , the end part is the Dispose method.However despite of being attractive this construct has a serious caveat that comes fro... | using ( new Tag ( `` body '' ) ) { Trace.WriteLine ( `` hello ! `` ) ; } // ... class Tag : IDisposable { String name ; public Tag ( String name ) { this.name = name ; Trace.WriteLine ( `` < `` + this.name + `` > '' ) ; Trace.Indent ( ) ; } public void Dispose ( ) { Trace.Unindent ( ) ; Trace.WriteLine ( `` < / '' + th... | `` using '' construct and exception handling |
C# | In .net fx i can doBut when looking at .net core or .net standard there is no more a culture parameter that can be passed . There is only string.ToLower ( ) and string.ToLowerInvariant ( ) Should the culture just be ommitted ? But should n't then there be issues when the culture of the string is not the current culture... | myString.ToLower ( frenchCulture ) ; | .net core / standard string.ToLower ( ) has no culture parameter |
C# | I 'm trying to generate a bit pattern ( repetitive strings ) and export into a text file , Here 's my code : Result : Now if I change the loop value to `` 20 '' , Result : I get this funny little rectangle boxes , could somebody please suggest me , what am I doing wrong here ? ? Many thanks for your time.. : ) | string pattern_01010101 = `` '' ; for ( int i = 0 ; i < 10 ; i++ ) { pattern_01010101 += `` 0,1,0,1,0,1,0,1 , '' ; } System.IO.File.WriteAllText ( @ '' C : \BField_pattern_01010101.txt '' , pattern_01010101 ) ; string pattern_01010101 = `` '' ; for ( int i = 0 ; i < 20 ; i++ ) { pattern_01010101 += `` 0,1,0,1,0,1,0,1 ,... | How to generate repetitive bit pattern ( strings ) & export into text file ? |
C# | Trying with a Diagnostic and a CodeFix to make a code who transform that : Into : Already done the diagnostic ( it works ) : Edit : I 've made some change.Now the incrementating is always recognized . The program go in the CodeFix , but my ReplaceToken with a SyntaxFactory do n't work . ( It 's now only for `` ++ '' an... | variable = variable + 1 ; otherVariable = otherVariable -1 ; variable++ ; otherVariable -- ; var incrementing = node as BinaryExpressionSyntax ; if ( incrementing ! = null ) { string right = incrementing .Right.ToString ( ) ; string left = incrementing .Left.ToString ( ) ; if ( right == left + `` - 1 '' || right == lef... | Roslyn C # incrementing change |
C# | Given a collection of Tasks : I would like to process the results of GetPricesAsync ( ) in whatever order they arrive . Currently , I 'm using a while loop to achieve this : Is this a problem that can be solved more elegantly using Rx ? I tried to use something like the code below but got stuck because somewhere I 'd h... | var americanAirlines = new FlightPriceChecker ( `` AA '' ) ; ... var runningTasks = new List < Task < IList < FlightPrice > > > { americanAirlines.GetPricesAsync ( from , to ) , delta.GetPricesAsync ( from , to ) , united.GetPricesAsync ( from , to ) } ; while ( runningTasks.Any ( ) ) { // Wait for any task to finish v... | How to turn a list of Tasks into an Observable and process elements as they are completed ? |
C# | Im not sure because in Java getter/setter are looking a little bit different but whats the `` c # way '' to code this stuff ? Option a. ) b. ) c . ) Ok there are some examples . What would look better ? Should I write all the private variable declarations first then the properties or should I group my variable and prop... | private string name ; public string Name { get { return name ; } set { name = value ; } } private int time ; public int Time { get { return time ; } set { time = value ; } } private string _name ; private int _time ; public string name { get { return _name ; } set { _name = value ; } } public int time { get { return _t... | How should I use Properties in C # ? |
C# | In our ASP.Net MVC 3 application we 're getting truncated strings on our forms when the string value contains a double-quote.For example , given a textbox : If the user enters the string : 'Hampshire '' County ' , when rendering the value back out to the form , only the string 'Hampsire ' is displayed . If I inspect th... | @ Html.TextBoxFor ( m = > m.County ) | Truncated strings with TextBoxFor |
C# | I was just reading an SO question on Python , and noticed the lack of parentheses in a for-loop . Looked nice to me , then I wondered : why does C # require them ? For example , I currently need to write : andSo I am wondering why I ca n't write : Is there a syntactic ambiguity in that statement that I am unaware of ? ... | if ( thing == stuff ) { } foreach ( var beyonce in allthesingleladies ) { } if thing == stuff { } if ( thing == stuff ) dostuff ( ) ; | Why does C # require parens around conditionals ? |
C# | I have an array consisting of following elements : The real object that i try to flatten is from importing data into array of arrays from CSV and then joining it on values of fields : I want to flatten that array of strings to get : I already have an solution that does that in loop , its not so performance-wise , but i... | var schools = new [ ] { new object [ ] { new [ ] { `` 1 '' , '' 2 '' } , `` 3 '' , '' 4 '' } , new object [ ] { new [ ] { `` 5 '' , '' 6 '' } , `` 7 '' , '' 8 '' } , new object [ ] { new [ ] { `` 9 '' , '' 10 '' , '' 11 '' } , `` 12 '' , '' 13 '' } } ; var q = from c in list join p in vocatives on c.Line [ name1 ] .ToU... | How do I flatten an array of arrays ? |
C# | I am writing code that interfaces with an external API that I can not change : It 's important that I call the correct overloaded method when reading data into buffer , but once the data is read in , I will process it generically . My first pass at code that does that was : C # , though , wo n't convert from T [ ] to b... | public class ExternalAPI { public static void Read ( byte [ ] buffer ) ; public static void Read ( int [ ] buffer ) ; public static void Read ( float [ ] buffer ) ; public static void Read ( double [ ] buffer ) ; } public class Foo < T > { T [ ] buffer ; public void Stuff ( ) { ExternalAPI.Foo ( buffer ) ; } } public c... | Is it possible to force an external class to call a specialized overload when the calling class is , itself , generic ? |
C# | The code below produces this error in Visual Studio 2012 ; `` A local variable named ' x ' can not be declared in this scope because it would give a different meaning to ' x ' , which is already used in a 'child ' scope to denote something else '' However . When modified as below I get this error ; `` The name ' x ' do... | for ( int x = 0 ; x < 9 ; x++ ) { //something } int x = 0 ; for ( int x = 0 ; x < 9 ; x++ ) { //something } x = 0 ; | For loop counter variable scope seems to have a dual personality ? |
C# | Im working on an existing Windows Service project in VS 2013.I 've added a web API Controller class I cant remember now if its a ( v2.1 ) or ( v1 ) controller class ... .Anyway I 've called it SyncPersonnelViaAwsApiControllerIm trying to call it from a AWS lambda ... so If I call the GETwith const req = https.request (... | public string Get ( int id ) { return `` value '' ; } const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/SapCall ' , ( res ) = > { //// POST api/ < controller > public string SapCall ( [ FromBody ] string xmlFile ) { string responseMsg = `` Failed Import User '' ; if ( ! IsNewestVersionO... | can use API GET but not API POST |
C# | Given that I have three tables , Vehicles , Cars , Bikes . Both Cars and Bikes have a VehicleID FK that links back to Vehicles.I want to count all vehicles that are cars like this.However , this will give me ALL the rows of vehicles and put null in the rows where the vehicle type is Bikes.I 'm using linqpad to do this ... | Vehicles.Select ( x= > x.Car ) .Count ( ) ; Vehicles.Select ( x= > x.Car.CountryID ) .Distinct ( ) .Dump ( ) ; InvalidOperationException : The null value can not be assigned to a member with type System.Int32 which is a non-nullable value type . Vehicles.Where ( x= > x.Car ! =null ) .Select ( x= > x.Car.CountryID ) .Di... | linq to sql : specifying JOIN instead of LEFT OUTER JOIN |
C# | I 've created a user control in a Windows Application C # 3.5 and it has a number of properties ( string , int , color etc ) . These can be modified in the properties window and the values are persisted without problem.However I 've created a property likeThe properties dialog allows me to add and remove these items , ... | public class MyItem { public string Text { get ; set ; } public string Value { get ; set ; } } public class MyControl : UserControl { public List < MyItem > Items { get ; set ; } } | .Net WinForm application not persisting a property of type List < MyClass > |
C# | During a demo I saw a piece of test code where the developer had pasted an url in the code . And when the developer build the application everything worked , but we where all very curious why the compiler accepted the url as a line.Why does the code above build ? Does the compiler treat the line as a comment ? | public class Foo { // Why does n't 'http : //www.foo.org ' break the build ? public void Bar ( ) { http : //www.foo.org Console.WriteLine ( `` Do stuff '' ) ; } } | Url in code not breaking build |
C# | In my Word add-in , I have a Word Document object which contains a particular Section . In this Section , I append a Shape : My issue is that some Word document templates have images or other things that appear over top of my shape . Originally , I thought that setting the Z order would be enough to fix this : It did n... | var shape = section.Headers [ WdHeaderFooterIndex.wdHeaderFooterFirstPage ] .Shapes.AddTextEffect ( MsoPresetTextEffect.msoTextEffect1 , `` Example text ... '' , `` Calibri '' , 72 , MsoTriState.msoFalse , MsoTriState.msoFalse , 0 , 0 , section.Headers [ WdHeaderFooterIndex.wdHeaderFooterFirstPage ] .Range ) as Shape ;... | Making a Shape top-most |
C# | I would like to be able to write the following in a LINQ query : to use this code , I have the following method : How do I write this method so that the query stated above would work ? | from item in listcollate by item.Propertyselect item ; public static IEnumerable < T > CollateBy < T , TKey > ( this IEnumerable < T > arr , Func < T , TKey > keySelector ) { foreach ( var group in arr.GroupBy ( keySelector ) ) { foreach ( var item in group ) yield return item ; } } | Extend the options of LINQ |
C# | I am drawing a rectangle in the paint method of a control . There is a zoom factor to consider , e.g . each positive MouseWheel event causes the control to repaint and then the rectangle gets bigger . Now I am drawing a string inside this rectangle , but I could n't figure out how to relate the font size of the text to... | public GateShape ( Gate gate , int x , int y , int zoomFactor , PaintEventArgs p ) { _gate = gate ; P = p ; StartPoint = new Point ( x , y ) ; ShapeSize = new Size ( 20 + zoomFactor * 10 , 20 + zoomFactor * 10 ) ; Draw ( ) ; } public Bitmap Draw ( ) { # if DEBUG Debug.WriteLine ( `` Drawing gate ' '' + _gate.GetGateTyp... | Dynamic font size to draw string inside a rectangle |
C# | I have a system that displays entries ordered by one of three fields , the most popular Today , This Week and This Month . Each time an entry is viewed the score is incremented by 1 thus changing the order.So if entry 1 is new and viewed 10 times today its scores will be : The Current SolutionAt the moment I simply hav... | Today : 10Week : 10Month : 10 Array size = 31 * 24 = 744 int16 values hours [ 4 ] ++ Memory per Entry = 3 * 4 bytes = 12 bytes ( Existing ) Memory per Entry = 744 * 2 = 1,488 bytes ( possible solution ) | Popular Today , This Week , This Month - Design Pattern |
C# | I have a Visual Studio 2008 C # .NET 3.5 project where a class listens for an event invocation from another class that is multithreaded . I need to ensure that my event only allows simultaneous access to a maximum of 10 threads . The 11th thread should block until one of the 10 finishes.I do not have control over the o... | myobj.SomeEvent += OnSomeEvent ; private void OnSomeEvent ( object sender , MyEventArgs args ) { // allow up to 10 threads simultaneous access . Block the 11th thread . using ( SomeThreadLock lock = new SomeThreadLock ( 10 ) ) { DoUsefulThings ( args.foo ) ; } } | A function that only permits N concurrent threads |
C# | People here are using visual studio for performance testing . Now there are some small issues with some javascript parts : they are not able to check the performance of the javascript part with visual studio web-performance testing.I never used visual studio performance test , so I really have no idea how to bench stuf... | var begin = new Date ( ) ; functionA ( ) ; functionB ( ) ; functionX ( ) ; var end = new Date ( ) ; var bench = end - begin ; | Read JS variable in C # / Forwarding JS variable to visual studio performance test ? |
C# | I have come across some unit tests written by another developer that regularly use an overloaded version of Assert.AreEqual like so : stringParamX is set within the unit test and stringparamY will be the result from the system under test.It is possible hat this code may be ported to other countries and these tests may ... | Assert.AreEqual ( stringparamX , stringParamY , true , CultureInfo.InvariantCulture ) ; | When to pass Culture when comparing strings using Assert.AreEqual ( ) in C # |
C# | I use LINQ-SQL as my DAL , I then have a project called DB which acts as my BLL . Various applications then access the BLL to read / write data from the SQL Database.I have these methods in my BLL for one particular table : All pretty straight forward I thought.Get_SystemSalesTaxListByZipCode is always returning a null... | public IEnumerable < SystemSalesTaxList > Get_SystemSalesTaxList ( ) { return from s in db.SystemSalesTaxLists select s ; } public SystemSalesTaxList Get_SystemSalesTaxList ( string strSalesTaxID ) { return Get_SystemSalesTaxList ( ) .Where ( s = > s.SalesTaxID == strSalesTaxID ) .FirstOrDefault ( ) ; } public SystemSa... | What 's the difference between these LINQ queries ? |
C# | Problem : Displaying large amounts of data in a scrollable area has horrible performance and/or User eXperience.Tried : Basically set a DataTemplate in a ListBox to show a grid of populated data with the VirtualizationMode set to Recycle and a fixed height set on the ListBox iteself . Something like the example below.T... | < ListBox x : Name= '' Items '' TabNavigation= '' Once '' VirtualizingStackPanel.VirtualizationMode= '' Recycling '' Height= '' 500 '' > < ListBox.ItemTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' Margin= '' 0,5 '' > < HyperlinkButton Content= '' Action '' Margin= '' 5 '' / > < ContentControl c... | Virtualization Performance Issue with Large Scrollable Data SL4 |
C# | I have a C # web api which I use to access an F # library . I have created a DU of the types I want to return and use pattern matching to choose which is return back to the c # controller . In the C # controller how do I access the data of the type which is return from the function call to the F # library ? C # Control... | public HttpResponseMessage Post ( ) { var _result = Authentication.GetAuthBehaviour ( ) ; //Access item1 of my tuple var _HTTPStatusCode = ( HttpStatusCode ) _result.item1 ; //Access item2 of my tuple var _body = ( HttpStatusCode ) _result.item2 ; return base.Request.CreateResponse ( _HTTPStatusCode , _body ) ; } modul... | Working with F # types in C # |
C# | I 'm working on a neural networks project and I have 2 classes like this : When I try to create network and display it 's `` contents '' : When I run that code - I 'm getting something like this ( all weights are identical ) : When I saw it - I tried to debug and find my mistake . However , when I put breakpoint in the... | public class Net { // Net object is made of neurons public List < Neuron > Neurons = new List < Neuron > ( ) ; // neurons are created in Net class constructor public Net ( int neuronCount , int neuronInputs ) { for ( int n = 0 ; n < neuronCount ; n++ ) { Neurons.Add ( new Neuron ( n , neuronInputs ) ) ; } } } public cl... | Very weird - code ( with Random ) works different when I use breakpoint |
C# | When we connect to a database in ASP.NET you must specify the appropriate connection string . However most other instances where data is to be specified is done within an object.For example why could n't we have connection objects such as : which is far better than some key/value string : Data Source=myServerAddress ; ... | var connection = new connectionObject ( ) { DataSource = `` myServerAddress '' , IntialCatalog = `` myDataBase '' , UserId = `` myUsername '' , Password = `` myPassword '' } | Why do we need connection strings ? |
C# | I 'm wondering if someone else can come up with a better way of simplifying relative URLs on either the basis of System.Uri or other means that are available in the standard .NET framework . My attempt works , but is pretty horrendous : This gives , for example : The problem that makes this so awkward is that Uri itsel... | public static String SimplifyUrl ( String url ) { var baseDummyUri = new Uri ( `` http : //example.com '' , UriKind.Absolute ) ; var dummyUri = new Uri ( baseDummyUri , String.Join ( `` / '' , Enumerable.Range ( 0 , url.Split ( new [ ] { `` .. '' } , StringSplitOptions.None ) .Length ) .Select ( i = > `` x '' ) ) ) ; v... | Simplify a relative URL |
C# | I have some code in a WPF application that looks like this : The dispose method is never getting explicitly called so the destructor calls it . It seems like in this case the object would be destroyed before the delegate in the BeginInvoke fires on the UI thread . It appears to be working though . What is happening her... | public class MyTextBox : System.Windows.Controls.TextBox , IDisposable { public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { Dispatcher.BeginInvoke ( ( Action ) delegate { // do work on member variables on the UI thread . } ) ; } ~MyTextBox (... | Calling BeginInvoke from a destructor |
C# | Is there a performance/memory usage difference between the two following property declarations , and should one be preferred ? Also , does the situation change if the Boolean is replaced with a different immutable value ( e.g . string ) ? | public bool Foo = > true ; public bool Foo { get ; } = true ; | Get-only property with constant value , auto-property or not ? |
C# | So I 've been going through various problems to review for upcoming interviews and one I encountered is determining whether two strings are rotations of each other . Obviously , I 'm hardly the first person to solve this problem . In fact , I did discover that my idea for solving this seems similar to the approach take... | public bool AreRotations ( string a , string b ) { if ( a == null ) throw new ArgumentNullException ( `` a '' ) ; else if ( b == null ) throw new ArgumentNullException ( `` b '' ) ; else if ( a.Trim ( ) .Length == 0 ) throw new ArgumentException ( `` a is empty or consists only of whitespace '' ) ; else if ( b.Trim ( )... | How to generalize my algorithm to detect if one string is a rotation of another |
C# | The Code PartImage Unfortunately this menu does not appear after I transform html file to aspx , what am I missing ? Do I missing something to enable ? Since the order of index.html file is absolutely the same with index.aspx , just I want to see the js powered menu . please help ! I just released that when I remove fr... | < script src= '' /c/Currency.js '' type= '' text/javascript '' > < /script > < form id= '' form1 '' runat= '' server '' > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' EnablePageMethods= '' true '' > < /asp : ScriptManager > < div id= '' Content '' > < div class= '' nobg '' > < div id= '' Top '' > ... | Covered from html to aspx page , but the menus disappeared , why ? |
C# | C # does n't allow lambda functions to represent iterator blocks ( e.g. , no `` yield return '' allowed inside a lambda function ) . If I wanted to create a lazy enumerable that yielded all the drives at the time of enumeration for example , I 'd like to do something likeIt took a while , but I figured out this as a wa... | IEnumerable < DriveInfo > drives = { foreach ( var drive in DriveInfo.GetDrives ( ) ) yield return drive ; } ; var drives = Enumerable.Range ( 0 , 1 ) .SelectMany ( _ = > DriveInfo.GetDrives ( ) ) ; | How to create an IEnumerable to get all X lazily in a single statement |
C# | In this piece of codeWhy does my Javascript recognize Model.IntegerParameter correctly but Model.StringParameter as null ? I am sure it has data on it as I check the response and it shows like thisMy View model is really simple and it looks like thisHow do I fix this ? Added InfoI tried changing the second parameter to... | @ using ( Ajax.BeginForm ( `` MyAction '' , `` MyRouteValues '' , new AjaxOptions { OnSuccess = `` myJSFunction ( `` + Model.IntegerParameter + `` , ' '' + Model.StringParameter + `` ' ) '' } ) ) data-ajax-success= '' myJSFunction ( 111111 , & # 39 ; AAAAAA & # 39 ; ) '' public class MyViewModel { public int IntegerPar... | String Parameter in AjaxOption null on Submit but showing in Response |
C# | I am running a search algorithm which is fed at the start with a single seed . From this point on I expect the algorithm to behave in a deterministic fashion , which it largely does . I can largely verify this by looking at the 10,000th step , 20,000 step and seeing they are identical . What I am seeing different thoug... | 30s 60s 120s 120s473,962 948,800 1,890,668 1,961,532477,287 954,335 1,888,955 1,936,974473,441 953,049 1,895,727 1,960,875475,606 953,576 1,905,271 1,941,511473,283 951,390 1,946,729 1,949,231474,846 954,307 1,840,893 1,939,160475,052 952,949 1,848,938 1,934,243476,797 957,179 1,945,426 1,951,542475,034 476,599 473,831... | Why might my C # computation time be non-deterministic ? |
C# | So the question is in the header.What NHibernate users can do : How to mimic such behavior in EF 4 ? | var q1 = Source.Companies.ToFuture ( ) ; var q2 = Source.Items.ToFuture ( ) ; var q3 = Source.Users.ToFuture ( ) ; var compoundModel = new CompoundModel ( q1 , q2 , q3 ) ; // All data obtained in single database roundtrip // When the first to future statement is touched | Does an analog of the NHibernate.ToFuture ( ) extension method exist in the Entity Framework ? |
C# | I want to display the icons associated with files . This is n't a problem for file types associated with normal desktop applications but only for those associated with ( metro/modern ) apps.If a file type is associated with an app and I am using AsParallel ( ) , I get only the default unknown file type icon . To clarif... | < Window x : Class= '' FileIconTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < StackPanel > < TextBox x : Name= '' TxtFilename '' Text= '' x : \somef... | Ca n't get file icon for files associated with Windows apps when using AsParallel ( ) |
C# | Suppose we have created Entities model , what is preferred way to work with it ? I 'm personally could n't make up my mind..Using ModelAdapter : looks neat ; but , context is created/released a lot sometimes , objects lose contact with context ; Using context in place : effectivebut , code becomes messyMixed mode , com... | public statiс Product [ ] GetProducts ( ) { using ( Entities ctx = new Entities ( ) ) { return ctx.Product.ToArray ( ) ; } } Product [ ] ps = ModelAdapter.GetProducts ( ) ; // ... ModelAdapter.UpdateProduct ( p ) ; using ( Entities ctx = new Entities ( ) ) { Product [ ] ps = ctx.Product.ToArray ( ) ; // ... ctx.SaveCha... | Working with entity framework , preferred way ? |
C# | If I have a class SubOfParent which is a sub-class of Parent , and two methods : why does the first doStuff get called when I pass a SubOfParent type object ? Thanks for any insight on this ! | public static void doStuff ( Parent in ) { } public static void doStuff ( SubOfPArent in ) { } | basic question on method overloading |
C# | I want to test GetParameters ( ) to assert the returned value includes `` test= '' within the value . Unfortunately the method responsible for this is private . Is there a way I can provide test coverage for this ? The problem I have is highlighted below : The problem is that info.TagGroups equals null in my testThanks... | if ( info.TagGroups ! = null ) [ Test ] public void TestGetParameters ( ) { var sb = new StringBuilder ( ) ; _renderer.GetParameters ( sb ) ; var res = sb.ToString ( ) ; Assert.IsTrue ( res.IndexOf ( `` test= '' ) > -1 , `` blabla '' ) ; } internal void GetParameters ( StringBuilder sb ) { if ( _dPos.ArticleInfo ! = nu... | unit testing c # and issue with testing a private method |
C# | I wanted to make an array awaitable by implementing an extension methodbut even though IntelliSense says `` ( awaitable ) mytype [ ] '' , the compiler gives me an error when usingCalling await on a single object of mytype works fine . Why is that ? Am I doing something wrong ? Thanks for your help . | public static IAwaitable GetAwaiter ( this mytype [ ] t ) { return t.First ( ) .GetAwaiter ( ) ; } mytype [ ] t = new mytype [ ] { new mytype ( ) , new mytype ( ) } ; await t ; | await array ; by implementing extension method for array |
C# | I 'm looking for the fastest way to find all strings in a collection starting from a set of characters . I can use sorted collection for this , however I ca n't find convenient way to do this in .net . Basically I need to find low and high indexes in a collection that meet the criteria.BinarySearch on List < T > does n... | aaaaaaaaaaaaaaabbaaaaaaaaaaaaaabaaaaaaaaaaaaaabc ... zzzzzzzzzzzzzxxzzzzzzzzzzzzzyzzzzzzzzzzzzzzzzzzzzza | Fastest way to select all strings from list starting from |
C# | I 've got a ResourceDictionary in a xaml file that represents a skin in a folder on my hard drive in some random folder . Say D : \Temp2\BlackSkin.xaml.I 've set the permissions correctly to give full access so that 's not the issue.This ResourceDictionary BlackSkin.xaml references a BaseSkin.xaml like so : So I 'm loa... | < ResourceDictionary xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' { D : \Temp2\BaseSkin.xaml '' > < /ResourceDictionary.MergedDictionaries > Source= '' ... | How can I chain Resource Dictionaries that are externally loaded from disk , not included in project or assembly ? |
C# | ( This used to be a 2-part question , but since the second part is literally the important one , I decided to split this into two separate posts . See Using Serialization to copy entities between two ObjectContexts in Entity Framework for the second part.I want to create a fairly generic `` cloner '' of databases for m... | using ( var sourceContext = new EntityContext ( ) ) { var sourceConnection = ( EntityConnection ) sourceContext.Connection ; var targetConnectionBuilder = new EntityConnectionStringBuilder ( ) ; targetConnectionBuilder.ProviderConnectionString = GetTargetConnectionString ( ) ; targetConnectionBuilder.Provider = `` Syst... | `` Cloning '' EntityConnections and ObjectContexts in Entity Framework |
C# | Silly question , but why does the following line compile ? As you can see , I have n't entered in the second element and left a comma there . Still compiles even though you would expect it not to . | int [ ] i = new int [ ] { 1 , } ; | Why is this c # snippet legal ? |
C# | In the following code , I would have expected calling a.Generate ( v ) would have resulted in calling V.Visit ( A a ) , since when Generate is called this is of type A. Hoewever , it appears that this is seen as being an Inter instead . Is it possible to have the intended behaviour without explicitly implementing the (... | using System ; using System.Diagnostics ; namespace Test { class Base { } class Inter : Base { public virtual void Generate ( V v ) { // ` Visit ( Base b ) ` and not ` Visit ( A a ) ` is called when calling // A.Generate ( v ) . Why ? v.Visit ( this ) ; } } class A : Inter { } class B : Inter { } class V { public void ... | How does polymorphism work with undefined intermediate types in C # ? |
C# | I 've tried looking for an answer but could n't find it . The 'issue ' is simple : If I have a collection of items using linq as follows : And another collection of items using linq but without a ToList ( ) : If now I try to iterate each item with a foreach ( I did n't try while or other kind of iteration methods ) : I... | var items = db.AnyTable.Where ( x = > x.Condition == condition ) .ToList ( ) ; var items2 = db.AnyTable.Where ( x = > x.Condition == condition ) ; foreach ( var item in items ) { int i = 2 ; // Does n't matter , The important part is to put a breakpoint here . } foreach ( var item in items2 ) { int i = 2 ; // Does n't ... | Database is locked when inside a foreach with linq without ToList ( ) |
C# | In a current benchmark about mongodb drivers , we have noticed a huge difference in performance between python and .Net ( core or framework ) .And the a part of the difference can be explained by this in my opinion.We obtained the following results : We took a look to the memory allocation in C # and we noticed a ping ... | ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━━━┫┃ Ratio Duration/Document ┃ 24.82 ┃ 0.03 ┃ 0.001 ┃┃ Duration ( ms ) ┃ 49 638 ┃ 20 016 ┃ 0.40 ┃┃ Count ┃ 2000 ┃ 671 972 ┃ 336 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━... | How to reach the same performance with the C # mongo driver than PyMongo in python ? |
C# | As I understand , generics is an elegant solution to resolve issues with extra boxing/unboxing procedures which occur within generic collections like List . But I can not understand how generics can fix problems with using interfaces within a generic function . In other words , if I want to pass a value instance which ... | public class main_class { public interface INum < a > { a add ( a other ) ; } public struct MyInt : INum < MyInt > { public MyInt ( int _my_int ) { Num = _my_int ; } public MyInt add ( MyInt other ) = > new MyInt ( Num + other.Num ) ; public int Num { get ; } } public static a add < a > ( a lhs , a rhs ) where a : INum... | Generics and usage of interfaces without boxing of value instances |
C# | I 'm developing a wp7 game where the player draws lines in the program and a ball bounces off of them . I 'm using XNA and farseer physics . What is the best method for a user to draw a line , and then for the program to take it and turn it in to a physics object , or at least a list of vector2s ? I 've tried creating ... | foreach ( TouchLocation t in input.TouchState ) { pathManager.Update ( gameTime , t.Position ) ; } public void Update ( GameTime gameTime , Vector2 touchPosition ) { paths.Add ( new Path ( world , texture , new Vector2 ( 5,5 ) ,0.1f ) ) ; paths [ paths.Count-1 ] .Position = touchPosition ; } public Path ( World world ,... | What is the best method in XNA to have the player paint smoothly on the screen ? |
C# | I have a factory class and CreateInstance methodThe factory can instantiate two differents subtypes depending on the value of tipoParametroEntita.TipoCampo.IdTipoCampo The point is the second argument of CreateInstance ( parametroEntitaMultiValoreDataSourceProvider ) is used only for creating instance of TipoEntitaTipo... | CreateInstance ( EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita , IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider ) public class TipoEntitaTipoParametroEntitaFactory : ITipoEntitaTipoParametroEntitaFactory { /// < summary > /// Creates an instance of TipoEntitaT... | Factory CreateInstance argument method not necessary for a specific subtype |
C# | I 'm trying to write a method for coverting a given object to an instance of a given type . I started with this : Going in , I know that is n't going to work , but it illustrates the concept . Now , I 'm going to start having problems when I have types that wo n't cast automatically , like string -- > DateTime . I was ... | private static T TryCast < T > ( object o ) { return ( T ) o ; } private static T TryCast < T > ( object o ) { var typeName = typeof ( T ) .FullName ; switch ( typeName ) { case `` System.String '' : return ( T ) Convert.ToString ( o ) ; default : return ( T ) o ; } } private static T TryCast < T > ( object o ) { retur... | C # Help me with some Generic casting awesomeness |
C# | After seeing how double.Nan == double.NaN is always false in C # , I became curious how the equality was implemented under the hood . So I used Resharper to decompile the Double struct , and here is what I found : This seems to indicate the the struct Double declares a constant that is defined in terms of this special ... | public struct Double : IComparable , IFormattable , IConvertible , IComparable < double > , IEquatable < double > { // stuff removed ... public const double NaN = double.NaN ; // more stuff removed ... } | When is a System.Double not a double ? |
C# | I was going through some old code that was written in years past by another developer at my organization . Whilst trying to improve this code , I discovered that the query it uses had a very bad problem . The problem is that the column a.RRRAREQ_TRST_DESC does not exist . A fact you learn very quickly when running it i... | OdbcDataAdapter financialAidDocsQuery = new OdbcDataAdapter ( @ '' SELECT a.RRRAREQ_TREQ_CODE , b.RTVTREQ_SHORT_DESC , a.RRRAREQ_TRST_DESC , RRRAREQ_STAT_DATE , RRRAREQ_EST_DATE , a.RRRAREQ_SAT_IND , a.RRRAREQ_SBGI_CODE , b.RTVTREQ_PERK_MPN_FLAG , b.RTVTREQ_PCKG_IND , a.RRRAREQ_MEMO_IND , a.RRRAREQ_TRK_LTR_IND , a.RRRA... | The riddle of the working broken query |
C# | What 's the best way to fix the below synchronization issue by enhancing OrderManager ? OrderForm needs to get the latest list of orders and trades and subscribe to those events while OrderManager generates order and trade by another thread.Should I remove event pattern and implement like this ? Any other better way ? | public class OrderManager { public event EventHandler < OrderEventArgs > OrderAdded ; public event EventHandler < OrderEventArgs > OrderUpdated ; public event EventHandler < OrderEventArgs > OrderDeleted ; public event EventHandler < TradeEventArgs > TradeAdded ; public List < Order > Orders { get ; private set ; } pub... | Synchronization issue in multiple event subscriptions and getting latest snapshot |
C# | I had C/C++ background . I came across a strange way of exchanging two values in C # . In C # , the above two lines do swap values between n1 and n2 . This is a surprise to me as in C/C++ , the result should be n1=n2=20 . So , how does C # evaluate an expression ? It looks like the + above is treated as a function call... | int n1 = 10 , n2=20 ; n2 = n1 + ( n1=n2 ) *0 ; | How does C # evaluate expressions which contain assignments ? |
C# | I 'm writing a generic code that should handle situations when data is loaded from multiple sources . I have a method with following signature : But it 's an overkill : when I pass TResult , I already know what TContract and TSection exactly are . In my example : But I have to write following : You can see that I have ... | public static TResult LoadFromAnySource < TContract , TSection , TResult > ( this TSection section , string serviceBaseUri , string nodeName ) where TSection : ConfigurationSection where TResult : IDatabaseConfigurable < TContract , TSection > , new ( ) where TContract : new ( ) public interface ISourceObserverConfigur... | Simplify generic type inferring |
C# | I am trying to find an alternative to the following so that I can take advantage of the is operator.Something similar to the following , which does not compile . | public bool IsOfType ( Type type ) { return this._item.GetType ( ) == type ; } public bool IsOfType ( Type type ) { return this._item is type ; } | Is there a way to pass an argument to the is operator ? |
C# | Watching Advanced Memory Management by Mark Probst and Rodrigo Kumpera , I learned new techniques such as profiling Mono GC and using WeakReference.Yet I still do n't understand how to “ fix ” the Puzzle 2 from 28th minute : The controller holds a ref to button that holds a ref to event handler that holds a ref to the ... | public class CustomButton : UIButton { public CustomButton ( ) { } } public class Puzzle2Controller : UIViewController { public override void ViewDidLoad ( ) { var button = new CustomButton ( ) ; View.Add ( button ) ; button.TouchUpInside += ( sender , e ) = > this.RemoveFromParentViewController ( ) ; } } | How do I fix the GC cycle caused by a lambda event handler ? |
C# | We use the .NET 2.0 framework with C # 3.0 ( I think it 's the last version of C # which can run on the 2.0 version of the framework , correct me if I am wrong ) .Is there something built into C # which can make this type of parameter validation more convenient ? That sort of parameter validation becomes a common patte... | public ConnectionSettings ( string url , string username , string password , bool checkPermissions ) { if ( username == null ) { throw new ArgumentNullException ( `` username '' ) ; } if ( password == null ) { throw new ArgumentNullException ( `` password '' ) ; } if ( String.IsNullOrEmpty ( url ) ) { throw new Argumen... | Nicer way of parameter checking ? |
C# | Let 's say I have a generic list of Fruit ( List < Fruit > fruits = new List < Fruit > ( ) ) . I then add a couple of objects ( all derived from Fruit ) - Banana , Apple , Orange but with different properties on the derived objects ( such as Banana.IsYellow ) .Then I can do this : But at execution time of course this i... | List < Fruit > fruits = new List < Fruit > ( ) ; Banana banana1 = new Banana ( ) ; Banana banana2 = new Banana ( ) ; Apple apple1 = new Apple ( ) ; Orange orange2 = new Orange ( ) ; fruits.Add ( banana1 ) ; fruits.Add ( banana2 ) ; fruits.Add ( apple1 ) ; fruits.Add ( orange1 ) ; foreach ( Banana banana in fruits ) Con... | How do I get a particular derived object in a List < T > ? |
C# | Possible Duplicate : C # Captured Variable In Loop I 'm working on a few simple applications of threading , but I ca n't seem to get this to work : The goal basically is to add threads to a queue one by one , and then to go through the queue one by one and pop off a thread and execute it . Because I have `` x < 2 '' in... | class ThreadTest { static Queue < Thread > threadQueue = new Queue < Thread > ( ) ; static void Main ( ) { //Create and enqueue threads for ( int x = 0 ; x < 2 ; x++ ) { threadQueue.Enqueue ( new Thread ( ( ) = > WriteNumber ( x ) ) ) ; } while ( threadQueue.Count ! = 0 ) { Thread temp = threadQueue.Dequeue ( ) ; temp.... | Simple Threading in C # |
C# | I 'm pretty sure this is related to implementing interfaces and inheritance.In c # how does the System.Type class have the property Name ? When I example the code of the Type class from metadata or using the Object Browser I see the Type class does n't have : defined anywhere . I also see that Type inherits from Member... | string Name public abstract class Type : MemberInfo , _Type , IReflect public abstract string Name { get ; } string Name { get ; } | How does c # System.Type Type have a name property |
C# | Why does expr1 compile but not expr2 ? | Func < object > func = ( ) = > new object ( ) ; Expression < Func < object > > expr1 = ( ) = > new object ( ) ; Expression < Func < object > > expr2 = func ; // Can not implicitly convert type 'System.Func < object > ' to 'System.Linq.Expressions.Expression < System.Func < object > > ' | Why does an Expression type in .NET allows construction from a function but not conversion from one ? |
C# | I 've noticed some bizarre behavior in my code when accidentally commenting out a line in a function during code review . It was very hard to reproduce but I 'll depict a similar example here.I 've got this test class : there is No assignment to Email in the GetOut which normally would throw an error : The out paramete... | public class Test { public void GetOut ( out EmailAddress email ) { try { Foo ( email ) ; } catch { } } public void Foo ( EmailAddress email ) { } } public struct EmailAddress { # region Constructors public EmailAddress ( string email ) : this ( email , string.Empty ) { } public EmailAddress ( string email , string nam... | out parameters of struct type not required to be assigned |
C# | Consider this code : in above code we do n't use method hiding.when create instance of student and call showinfo method my output is I am Student i do n't use new keyword.Why does not call parent method when we do n't use method hiding ? | internal class Program { private static void Main ( string [ ] args ) { var student = new Student ( ) ; student.ShowInfo ( ) ; //output -- > `` I am Student '' } } public class Person { public void ShowInfo ( ) { Console.WriteLine ( `` I am person '' ) ; } } public class Student : Person { public void ShowInfo ( ) { Co... | Why does not call parent method when we do n't use method hiding ? |
C# | I am using the default Sitemap provider with secutiry trimming . But , some how , I get : A network-related or instance-specific error occurred while establishing a connection to SQL Server . I 'm thinking the sitemap provider is looking for the roles in the wrong place . My configuration is like this : The Sitemap tag... | < connectionStrings > < add name= '' DB '' ... / > < /connectionStrings > < membership defaultProvider= '' SqlProvider '' userIsOnlineTimeWindow= '' 15 '' > < providers > < clear/ > < add name= '' SqlProvider '' ... / > < /providers > < /membership > < roleManager enabled= '' true '' > < providers > < add connectionStr... | Sitemap Security Trimming throws SQL error |
C# | When overriding the Equals ( ) method , the MSDN recommends this : But if we know that the subclass directly inherits from Object , then is the following equivalent ? Note the ! base.Equals ( ) call : | class Point : Object { protected int x , y ; public Point ( int X , int Y ) { this.x = X ; this.y = Y ; } public override bool Equals ( Object obj ) { //Check for null and compare run-time types . if ( obj == null || GetType ( ) ! = obj.GetType ( ) ) return false ; Point p = ( Point ) obj ; return ( x == p.x ) & & ( y ... | Overriding Equals ( ) : is null comparison redundant when calling base.Equals ( ) ? |
C# | I have a list of invoices that and I transferred them to an Excel spreadsheet . All the columns are created into the spreadsheet except for the Job Date column . That is blank in the spreadsheet . Here 's the code : The sql returns all the correct information and as you can see the job date is there : But when I open t... | string Directory = ConfigurationSettings.AppSettings [ `` DownloadDestination '' ] + Company.Current.CompCode + `` \\ '' ; string FileName = DataUtils.CreateDefaultExcelFile ( Company.Current.CompanyID , txtInvoiceID.Value , Directory ) ; FileInfo file = new FileInfo ( FileName ) ; Response.Clear ( ) ; Response.Content... | Column missing from excel spreedshet |
C# | Let 's say there is a class A with an parameterless instance methodIt 's easy to invoke the method using reflection : However , I want to invoke the method as if it is staticIs there any way I can get this staticmethod ? NOTE : I want Something to be universal , i.e . A can be any class , and foo can be any instance me... | class A { public A ( int x ) { this.x = x ; } private int x ; public int foo ( ) { return x ; } } A a = new A ( 100 ) ; var method = typeof ( A ) .GetMethod ( `` foo '' ) ; var result = method.Invoke ( a , new object [ 0 ] ) ; // 100 var staticmethod = Something ( typeof ( A ) , `` foo '' ) ; var result = staticmethod.... | Invoke instance method statically |
C# | I saw some code written by another developer that looks something like this : ( It is ALL over the place in the code ) Question 1 : Would that error logging code even get called ? If there was no memory , would n't an System.OutOfMemoryException be thrown on that first line ? Question 2 : Can a call to a constructor ev... | var stringBuilder = new StringBuilder ( ) ; if ( stringBuilder == null ) { // Log memory allocation error // ... return ; } | Would simple class instantiation ever fail in C # ? |
C# | I have system being developed for an HR system . There are Accountant employees and Programmer employees . For the first month of joining the company , the employee is not given any role . One employee can be an Accountant and a programmer at the same time . I have a design shown by the following code.Now , I need to e... | List < Accountant > allAccountants = Get All accountants from databasepublic class Employee { public int EmpID { get ; set ; } public DateTime JoinedDate { get ; set ; } public int Salary { get ; set ; } public bool IsActive { get ; set ; } } public class Accountant : Employee { public Employee EmployeeData { get ; set... | Issue in using Composition for “ is – a “ relationship |
C# | I wrote a Thread helper class that can be used to execute a piece of code in Unity 's main Thread . This is the functions blue print : The complete script is really long and will make this post unnecessarily long . You can see the rest of the script helper class here.Then I can use unity 's API from another Thread like... | public static void executeInUpdate ( System.Action action ) UnityThread.executeInUpdate ( ( ) = > { transform.Rotate ( new Vector3 ( 0f , 90f , 0f ) ) ; } ) ; bool doneUploading = false ; byte [ ] videoBytes = new byte [ 25000 ] ; public Texture2D videoDisplay ; void receiveVideoFrame ( ) { while ( true ) { //Download ... | Delegate Closure with no memory allocation |
C# | I want to create a .Net Core console app that gets run by the Windows Task Scheduler . In this console app I want to find the path of the directory where the app 's .exe file is located.I publish the app to create the .exe file by running this line of code in a command prompt : dotnet publish -r win-x64 -c Release /p :... | //program.csusing System ; using System.Diagnostics ; using System.IO ; using System.Reflection ; namespace PathTest { class Program { static void Main ( string [ ] args ) { Write ( Directory.GetCurrentDirectory ( ) ) ; Write ( Assembly.GetExecutingAssembly ( ) .Location ) ; Write ( Assembly.GetExecutingAssembly ( ) .C... | How to get the path of the directory where the .exe file for a .Net Core console application is located ? |
C# | So in C # , you might have the following code : As soon as you enter DoSomething , the CLR sets up space for int x . Why does it not wait until it reaches the line with int x =5 on it ? Especially since even though x is bound , it does n't let you actually use it until that line is reached anyway ? | void DoSomething ( ) { //some code . int x = 5 ; //some more code . } | Why does C # bind the local variables up-front ? |
C# | If you have a brush and pen as in : and dispose them like so : How would you dispose it if it was : Pen p = CreatePenFromColor ( color ) which would create the brush and pen for you ? I ca n't dispose the brush inside this method , right ? Is this a method not to be used with disposable objects ? EDIT : What I mean is ... | Brush b = new SolidBrush ( color ) ; Pen p = new Pen ( b ) ; b.Dispose ( ) ; p.Dispose ( ) ; | How to handle disposable objects we do n't have a reference to ? |
C# | BackgroundI have an application where 3 views utilize html5 offline app functionality . As such , I have an app manifest generated in a razor view . A cut-down version of this view may look like the following : In order for the offline app to function correctly , the cached files must exactly match those requested by o... | CACHE MANIFESTCACHE : /site.min.css/site.min.js @ inject FileVersionProvider versionProviderCACHE MANIFESTCACHE : @ versionProvider.AddFileVersionToPath ( `` /site.min.css '' ) @ versionProvider.AddFileVersionToPath ( `` /site.min.js '' ) services.AddSingleton < FileVersionProvider > ( s = > new FileVersionProvider ( s... | Service/extension for getting a cache-busting 'version string ' |
C# | I have the following extension method to find an element within a sequence , and then return two IEnumerable < T > s : one containing all the elements before that element , and one containing the element and everything that follows . I would prefer if the method were lazy , but I have n't figured out a way to do that .... | public static PartitionTuple < T > Partition < T > ( this IEnumerable < T > sequence , Func < T , bool > partition ) { var a = sequence.ToArray ( ) ; return new PartitionTuple < T > { Before = a.TakeWhile ( v = > ! partition ( v ) ) , After = a.SkipWhile ( v = > ! partition ( v ) ) } ; } | Lazily partition sequence with LINQ |
C# | Here is the equality comparer I just wrote because I wanted a distinct set of items from a list containing entities.Why does Distinct require a comparer as opposed to a Func < T , T , bool > ? Are ( A ) and ( B ) anything other than optimizations , and are there scenarios when they would not act the expected way , due ... | class InvoiceComparer : IEqualityComparer < Invoice > { public bool Equals ( Invoice x , Invoice y ) { // A if ( Object.ReferenceEquals ( x , y ) ) return true ; // B if ( Object.ReferenceEquals ( x , null ) || Object.ReferenceEquals ( y , null ) ) return false ; // C return x.TxnID == y.TxnID ; } public int GetHashCod... | Questions about IEqualityComparer < T > / List < T > .Distinct ( ) |
C# | When implementing IEnumerable & IEnumerator on a class I was writing during training , I noticed that I was required to specify two implementations for the property `` Current '' .I roughly understand that I 'm implementing some non-generic version of IEnumerator and a `` Current '' property for it , however I do n't u... | public class PeopleEnumerator : IEnumerator < Person > { People people ; // my collection I 'm enumerating ( just a wrapped array ) . int index ; // my index to keep track of where in the collection I am . ... //implementation for Person public Person Current { get { return people [ index ] ; } } //implementation for o... | Why must I define IEnumerator < T > .Current & IEnumerator.Current , and what does that achieve ? |
C# | Sorry for the long question but I 'm kinda new to C # ( I used to use VB.Net ) I fully understand the difference between Overriding and Overloading in both VB.Net and C # .. so there 's no problem with the overriding.Now , in VB.Net there 's a difference between Shadowing ( using the keyword Shadows ) and Overloading (... | Class A Sub MyMethod ( ) Console.WriteLine ( `` A.MyMethod '' ) End Sub Sub MyMethod ( ByVal x As Integer ) Console.WriteLine ( `` A.MyMethod ( x ) '' ) End Sub Sub MyMethod2 ( ) Console.WriteLine ( `` A.MyMethod2 '' ) End Sub Sub MyMethod2 ( ByVal x As Integer ) Console.WriteLine ( `` A.MyMethod2 ( x ) '' ) End SubEnd... | C # vs VB.Net , what 's the difference between Shadowing and [ Overloading ( without changing the arguments ) ] |
C# | I using Unity 2019.2.14f1 to create a simple 3D game.In that game , I want to play a sound anytime my Player collides with a gameObject with a specific tag.The MainCamera has an Audio Listener and I am using Cinemachine Free Look , that is following my avatar , inside the ThridPersonController ( I am using the one that... | using UnityEngine.Audio ; using System ; using UnityEngine ; public class AudioManager : MonoBehaviour { public Sound [ ] sounds ; // Start is called before the first frame update void Awake ( ) { foreach ( Sound s in sounds ) { s.source = gameObject.AddComponent < AudioSource > ( ) ; s.source.clip = s.clip ; s.source.... | Unity3D playing sound when Player collides with an object with a specific tag |
C# | It is my understanding that C # is a safe language and does n't allow one to access unallocated memory , other than through the unsafe keyword . However , its memory model allows reordering when there is unsynchronized access between threads . This leads to race hazards where references to new instances appear to be av... | if ( a == null ) { lock ( obj ) { if ( a == null ) a = new A ( ) ; } } byte [ ] buffer = new byte [ 2 ] ; Parallel.Invoke ( ( ) = > buffer = new byte [ 4 ] , ( ) = > Console.WriteLine ( BitConverter.ToString ( buffer ) ) ) ; | Can memory reordering cause C # to access unallocated memory ? |
C# | I am trying to use the SMO for Sql Server 2008 R2 Standard , but I am running into an issue whenever I try to Dump an object.The relevant code : Edit : A work around that I found is to use the Dump method with a fixed recursion depth e.g . Dump ( 1 ) , but the exception is at a different level for each object . | void Main ( ) { var connectionString = @ '' Server= ( local ) ; Trusted_Connection=True ; '' ; Server server = new Server ( new ServerConnection ( new SqlConnection ( connectionString ) ) ) ; server.ConnectionContext.Connect ( ) ; server.Dump ( ) ; //Error Database database = new Database ( server , `` master '' ) ; da... | Using LinqPad with SMO |
C# | Something I do often if I 'm storing a bunch of string values and I want to be able to find them in O ( 1 ) time later is : This way , I can comfortably perform constant-time lookups on these string values later on , such as : However , I feel like I 'm cheating by making the value String.Empty . Is there a more approp... | foreach ( String value in someStringCollection ) { someDictionary.Add ( value , String.Empty ) ; } if ( someDictionary.containsKey ( someKey ) ) { // etc } | 'Proper ' collection to use to obtain items in O ( 1 ) time in C # .NET ? |
C# | I would like to enumerate the strings that are in the string intern pool.That is to say , I want to get the list of all the instances s of string such that : Does anyone know if it 's possible ? | string.IsInterned ( s ) ! = null | Read the content of the string intern pool |
C# | I have encryption method that runs incredible slowly . It takes around 20 minutes to encrypt several hundred MB of data . I 'm not sure if I 'm taking the right approach . Any help , thoughts , advice would be greatly appreciated.Thanks for your help ! | private void AES_Encrypt ( string inputFile , string outputFile , byte [ ] passwordBytes , byte [ ] saltBytes ) { FileStream fsCrypt = new FileStream ( outputFile , FileMode.Create ) ; RijndaelManaged AES = new RijndaelManaged ( ) ; AES.KeySize = 256 ; AES.BlockSize = 128 ; var key = new Rfc2898DeriveBytes ( passwordBy... | How to Speed Up this Encryption Method C # Filestream |
C# | I have the following code : This code results in a compiler error : can not implicity convert type 'int ' to 'short'If I write the condition in the expanded format there is no compiler error : Why do I get a compiler error ? | Int16 myShortInt ; myShortInt = Condition ? 1 :2 ; if ( Condition ) { myShortInt = 1 ; } else { myShortInt = 2 ; } | cast short to int in if block |
C# | I made an extension method to find the number of consecutive values in a collection . Because it is generic , I allow the caller to define the `` incrementor '' which is a Func < > that is supposed to increment the value in order to check for the existence of a `` next '' value.However , if the caller passes an imprope... | public static int CountConsecutive < T > ( this IEnumerable < T > values , T startValue , Func < T , T > incrementor ) { if ( values == null ) { throw new ArgumentNullException ( `` values '' ) ; } if ( incrementor == null ) { throw new ArgumentNullException ( `` incrementor '' ) ; } var nextValue = incrementor ( start... | How do I avoid infinite recursion with a custom enumerator ? |
C# | I have a list of properties and their values and they are formatted in a Dictionary < string , object > like this : There are two classes . Person is composed of the string Name and primitive Age as well as the complex Address class which has House , Street , City , and State string properties.Basically what I want to ... | Person.Name = `` John Doe '' Person.Age = 27Person.Address.House = `` 123 '' Person.Address.Street = `` Fake Street '' Person.Address.City = `` Nowhere '' Person.Address.State = `` NH '' foreach ( ParameterInfo parameter in this.method.Parameters ) { Type parameterType = parameter.ParameterType ; object parameterInstan... | How can you translate a flat dotted list of properties to a constructed object ? |
C# | a ) Do s and s1 reference variables point to same string object ( I ’ m assuming this due to the fact that strings are immutable ) ? b ) I realize equality operators ( == , > etc ) have been redefined to compare the values of string objects , but is the same true when comparing two strings using static methods Object.E... | string s = `` value '' ; string s1 = `` value '' ; | Since strings are immutable , do variables with identical string values point to the same string object ? |
C# | I ca n't figure out the use for this code . Of what use is this pattern ? [ code repeated here for posterity ] | public class Turtle < T > where T : Turtle < T > { } | What use is this code ? |
C# | I 'm designing a linguistic analyzer for French text . I have a dictionary in XML format , that looks like this : Sorry it 's so long , but it 's necessary to show exactly how the data is modeled ( tree-node structure ) .Currently I am using structs to model the conjugation tables , nested structs to be more specific .... | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Dictionary > < ! -- This is the base structure for every entry in the dictionary . Values on attributes are given as explanations for the attributes . Though this is the structure of the finished product for each word , definition , context and context examples wil... | How to Represent Conjugation Tables in C # |
C# | I was wondering , An Instance of class is on the Heap . ( value types inside it are also in the heap ) .But what about the opposite case ? There is one question here but it did n't mention any GC related info.So - How does GC handle this situation ? | public struct Point { object o ; public int x , y ; public Point ( int p1 , int p2 ) { o = new Object ( ) ; x = p1 ; y = p2 ; } } | Struct with reference types and GC ? |
C# | I am trying to solve this business issue : A user gets 10 attempts to login every 5 minutesIf a user exceeds 10 attempts , I display a `` You need to wait tologin '' messageOnce 5 minutes have elapsed , I need to reset the number of attemptsand let the user attempt 10 more times.I 'd like to do this without using a Tim... | public class LoginExp { public DateTime FirstAttempt ; public int NumOfAttempts ; } | How to solve this Timeslot issue in C # |
C# | For all DI examples I have seen , I always see the dependencies as other classes , like services . But an object may depend , heavily and/or crucially in fact , on configuration values such as Strings and resource wrappers ( File/Path/URI/URL , as opposed to an entire big value string/document , or a reader ) .Note , t... | public abstract class PathResolver { protected File projectFilesLocation ; public RoutinePathResolver ( File projectFilesLocation ) { this.projectFilesLocation = projectFilesLocation ; } public abstract String getPath ( String someValue ) ; } | Are value objects valid dependencies for DI design pattern ? |
C# | I keep running into a pattern whereby I want to select rows from an Entity Collection ( EF4 ) and use the data to create new rows in a different entity collection.The only way I have found to do this is to perform the following steps : If I try to create a new OtherEntity in the select then I get an EF exception.Is thi... | var newEntities = ( from e in myentities where e.x == y select new { Prop1 = e.Prop1 , Prop2 = e.Prop2+e.Prop3 , Prop3 = DateTime.Now , Prop4 = `` Hardcodedstring '' } ) .AsEnumerable ( ) .Select ( n= > new OtherEntity { Prop1 = n.Prop1 , Prop2 = n.Prop2 , Prop3 = n.Prop3 , Prop4 = n.Prop4 } ) ; //insert into database ... | Is it necessary to always Select ( ) ... new { Anon } ... AsEnumerable ... Select ( new EntityType { } ) every time ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.