lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | When I type Alt+1 I get back ☺I would like some magic way in code to get the ☺ character in a string.Something like this : Then in the rich text box there should be this : ☺ | string smiley = AltCodes.GetAltCodeCharacter ( 1 ) .ToString ( ) ; // Display the SmileyrichTextBoxHappy.Text = smiley ; | How do I find a character matching my alt code |
C# | I want to rotate my player vehicle into the target object direction/side.Though the following image , I have tried to explain my point in better way : I want to rotate my below tank object towards another tank object so that it can point into that direction.I have written this code for this purpose but it is not workin... | IEnumerator DoRotationAtTargetDirection ( Transform opponentPlayer ) { Quaternion targetRotation = Quaternion.identity ; do { Debug.Log ( `` do rotation '' ) ; Vector3 targetDirection = opponentPlayer.position - transform.position ; targetRotation = Quaternion.LookRotation ( targetDirection ) ; Quaternion nextRotation ... | Smoothly Rotate Object Towards Target Object |
C# | Let 's say I have these 2 arrays : I want to loop over these and instead of thisI wonder if I , using LINQ , could somehow achieve something like thisJust doing a nested from like this does n't worksince that will repeat the inner from for each outer iteration . | const int length = 5 ; var ints = new int [ length ] { 1 , 2 , 3 , 4 , 5 } ; var strings = new string [ length ] { `` s1 '' , `` s2 '' , `` s3 '' , `` s4 '' , `` s5 '' } ; for ( var index = 0 ; index < length ; index++ ) { var i = ints [ index ] ; var s = strings [ index ] ; DoSomething ( i , s ) ; } var items = ... i ... | Combining collections of different types with LINQ |
C# | It 's looks so : It 's split `` ASds22d . asd ,156 '' to `` ASds22d '' + `` . '' + `` asd '' + `` , '' + `` 156 '' .Here is problem with strings like `` a-z '' , `` 0-9 '' or variations like `` a-c '' and `` 4-5 '' . My regex split `` a-z 1-9 '' to `` a '' + `` - '' + `` z '' + `` 1 '' + `` - '' + `` 9 '' but i need ju... | string [ ] lines = Regex.Split ( line , @ '' \s+| ( ? ! ^ ) ( ? =\p { P } ) | ( ? < =\p { P } ) ( ? ! $ ) '' ) ; | I have regex to split string to words , numbers and punctuation marks list . How to make `` a-z '' and `` 0-9 '' single elements of list ? |
C# | I am writing code with the factory pattern . In switch case , I am actually returning Class objects . Using this return class , I am going to call a method . Is this an example of strategy pattern ? Can you clear my misunderstanding here ? Is this code is an example of factory and strategy pattern both ? Thank you in a... | using System ; using System.Linq ; namespace ConsoleApplication1 { public interface IVehicle { void Manufacture ( ) ; } public class Car : IVehicle { public void Manufacture ( ) { Console.WriteLine ( `` Car Manufacturing '' ) ; } } public class Bike : IVehicle { public void Manufacture ( ) { Console.WriteLine ( `` Bike... | Strategy pattern used in Factory pattern ? |
C# | I have been using PLINQ recently to perform some data handling.Basically I have about 4000 time series ( so basically instances of Dictionary < DataTime , T > ) which I stock in a list called timeSeries.To perform my operation , I simply do : If I have a look at what is happening with my different cores , I notice that... | timeSeries.AsParallel ( ) .ForAll ( x= > myOperation ( x ) ) | Why does my Parallel.ForAll call end up using a single thread ? |
C# | I want to split camelCase or PascalCase words to space separate collection of words.So far , I have : It works fine for converting `` TestWord '' to `` Test Word '' and for leaving single words untouched , e.g . Testing remains Testing.However , ABCTest gets converted to A B C Test when I would prefer ABC Test . | Regex.Replace ( value , @ '' ( \B [ A-Z ] + ? ( ? = [ A-Z ] [ ^A-Z ] ) |\B [ A-Z ] + ? ( ? = [ ^A-Z ] ) ) '' , `` $ 0 '' , RegexOptions.Compiled ) ; | Ignore existing spaces in converting CamelCase to string with spaces |
C# | I am making an application to store tickets for boarding a place for a imaginary airline.I have created a Ticket class see belowI have two ticket classes , first and economy . The plane can only hold 10 seats . So my structure is having two arrays of ticket objects , one containing 4 ticket objects `` first class '' an... | public class ticket { String lastName ; String firstName ; String origin ; String destination ; String flightNumber ; String seatNumber ; String date ; public ticket ( ) { } public ticket ( String lastname , String firstName , String origin , String destination , String flightNumber , String seatNumber , String date ) ... | Type used as a variable error |
C# | Problem : Error message upon passing viewmodel to partial view.Main page : Index.cshmtl , uses class DivisionModelPartial view : _prtDivision.cshmtl , uses addDivisionViewModelHowever , when I pass 'addDivionsViewModel to the view.i.e . on index page in the tabpanel I get the below error message : Indicating the passed... | @ model DivisionViewModel @ { Layout = `` ~/Views/Shared/_Layout.cshtml '' ; } @ * < h2 > Division < /h2 > * @ < div > < ! -- Nav tabs -- > < ul class= '' nav nav-tabs '' role= '' tablist '' id= '' divTabs '' > < li role= '' presentation '' class= '' active '' > < a href= '' # home '' aria-controls= '' home '' role= ''... | Correct method of passing correct data model to partial view |
C# | I 'm in the process of doing a LINQ query of an object call Recipe that need to be ordered by it 's score . In the beginning , I have a IEnumberable of type Recipe ( already filtered with the search criteria ) called selectedRecipiesThen , with the help of my friend google , I have done this query using an anonymous ty... | var finalQuery = ( ( from h in db.StarRatings where selectedRecipies.Any ( sr = > sr.IDRecipe == h.IDRecipe ) group h by new { h.IDRecipe } into hh select new { hh.Key.IDRecipe , Score = hh.Sum ( s = > s.Score ) } ) .OrderByDescending ( i = > i.Score ) ) ; | LINQ anonymous type not giving the list I need |
C# | Lately in my Unity projects , I have discovered that to create a more modular application it helps to have a static List in a class that contains references to all or some of the objects created so that they may be accessed easily from other parts of the program . An example is below : This simply allows an object that... | private static List < Canvas > availableCanvases = new List < Canvas > ( ) ; void Start ( ) { availableCanvases.Add ( this ) ; } public static void AddComponentToCanvas ( Transform component ) { for ( int i = 0 ; i < availableCanvases ; i++ ) { //Make sure the canvas still exists if ( availableCanvases [ i ] ! = null )... | What is this programming method called ? And is it bad ? |
C# | I have read plenty of discussions and examples of how to make a property threadsafe . There is one on the page for this threadsafe wrapper classThe example given is this : It is clear what 's happening here , and what the locks are doing , but I 'm struggling to see why it is required . Why is the following not threads... | internal class MyThreadSafeCass { // *** Lock *** private object PropertyLock = new object ( ) ; // *** Property *** private int m_Property = 0 ; // *** Thread-safe access to Property using locking *** internal int Property { get { lock ( PropertyLock ) { return m_Property ; } } set { lock ( PropertyLock ) { m_Property... | What is non threadsafe about a simple property get set in c # ? |
C# | I want to use HaveBox for Dependency Injection . But it is n't question about HaveBox . So I created base controller : And my HomeController was inherited from BaseController . Add HaveBoxConfig.RegisterTypes ( ) ; to Application_Start method and implementation of HaveBoxConfig is : And my resolver : Method GetService ... | public abstract class BaseController : Controller { protected readonly IRepository m_Repository ; protected BaseController ( IRepository repository ) { m_Repository = repository ; } } public class HaveBoxConfig { public static void RegisterTypes ( ) { var container = new Container ( ) ; container.Configure ( config = >... | Dependency Injection does n't know about type that I want to inject |
C# | Consider the following classes : Quote fully encapsulates the functionality of both VehicleList and CoverageList so I 'd like to mark those classes as internal . The problem is that they are the types of protected fields of a public class . If I mark those fields as protected internal then they are protected OR interna... | public class Vehicle { ... } public class Coverage { ... } public class VehicleList : IEnumerable < Vehicle > { ... } public class CoverageList : IEnumerable < Coverage > { ... } public abstract class Quote { protected VehicleList vehicles ; protected CoverageList coverages ; internal Quote ( ) { ... } public IReadOnly... | Is an internal AND protected member possible in C # ? |
C# | I have a problem with a PaginatedList in a Web API project.In the repository there 's a method like : But , when I try to use it , like this : I get this error : Can not implicitly convert type 'int ' to 'Domain.Entities.Dictionaries.Region'What am I doing wrong ? | public virtual PaginatedList < T > Paginate < TKey > ( int pageIndex , int pageSize , Expression < Func < T , TKey > > keySelector , Expression < Func < T , bool > > predicate , params Expression < Func < T , object > > [ ] includeProperties ) { IQueryable < T > query = AllIncluding ( includeProperties ) .OrderBy ( key... | How to use Paginate method |
C# | I have this problem for sometime now but today I reached the tipping point and I 'm asking for your help.Suppose I have this code : I end up with this anonymous type and everything is fine . Now something comes up that makes me condition the Where clause , so I have to make a different query according to the condition ... | var query = DbContext.Table.Where ( x = > x.z == true ) .Select ( x = > new { x.a , x.b , x.c } ) ; foreach ( var item in query ) { // Do the work } if ( something ) { var query = DbContext.Table.Where ( x = > x.z == true & & x.zz == false ) .Select ( x = > new { x.a , x.b , x.c } ) ; foreach ( var item in query ) { //... | Creating an anonymous type depending on different conditions and casting it to a class |
C# | I have data in the following format : Datatypes : Date = Date , Person = String , Hours = IntegerUsing LINQ I would like to select it into this format : Datatypes : Date = Date , Sam = Integer , Sally = IntegerIs this possible ? | ( Table : Hours ) { Date = `` 21/04/2008 '' , Person = Sally , Hours= 3 } { Date = `` 21/04/2008 '' , Person = Sam , Hours = 15 } { Date = `` 22/04/2008 '' , Person = Sam , Hours = 8 } { Date = `` 22/04/2008 '' , Person = Sally , Hours = 9 } { Date = `` 21/04/2008 '' , Sam = 15 , Sally = 3 } { Date = `` 22/04/2008 '' ,... | Rearrange Table Data using Linq |
C# | I am trying to create a regular expression in C # that allows only alphabet characters and spaces.i just tried this . | [ Required ( ErrorMessage = `` Please Enter Name '' ) ] [ Display ( Name = `` Name '' ) ] [ RegularExpression ( `` ^ ( [ a-zA-Z ] ) '' , ErrorMessage = `` Please Enter Correct Name '' ) ] | .net regular expression integration |
C# | I 'm writing a program and found some common behavior , so I thought this would be an appropriate use case for an abstract base class.This is a simplified version of my Abstract Base Class : This is a simplified version of my Derived Class : This is the Generic Method that I want to operate on my derived classes : Up t... | public abstract class BehaviorClass < T > where T : IDomainObj { protected BehaviorClass ( var x ) { ... } public abstract void Create ( List < T > list , out string message ) ; public abstract void Delete ( List < T > list , out string message ) ; ... } public class DbSheets : BehaviorClass < Sheet > { public override... | Compiler gives implicit conversion error || My generic method 's constraint is an abstract generic class |
C# | What is a good usage of the is-operator ? The construct below for casting is not the recommended way to go , virtually all documentation prefers the as-operator with a null-check.And sure this is a ( very small ) performance increase and some even mention the tread safety.And yes this is true ... So , why do we have th... | if ( obj is SomeClass ) { SomeClass some = ( SomeClass ) obj ; ... . } | What is a good usage of the is-operator |
C# | int i = 0 ; When i value changes : i = ( Atypical value ) thenIn C # , How to get the value of a variable when it changes Without using threads or timers | bool callback ( int i ) target = i ; return true ; | In C # , How to get the value of a variable when it changes Without threads or timers |
C# | I have a row with 4 columns of data . I want to create an object A from data in columns 1-2 . If the data is not present in columns 1-2 , use columns 3-4 to create an object B . In rare cases , we will have data in all columns , but data in columns 2 and 4 does not match . In that case , I want to return an object A an... | public class A { public long ID { get ; set ; } public long Value { get ; set ; } } public class B { public long ID { get ; set ; } public long Value { get ; set ; } } | How can I create 1 or 2 objects per row with dapper ? |
C# | I noticed after some time using generics that there was not much difference between this : and this : The only difference I have seen so far is that the first method could be added other constraints , like interfaces or new ( ) , but if you use it just the way that I wrote it , I don´t see much difference . Can anybody... | public void DoSomething < T > ( T t ) where T : BaseClass { } public void DoSomething ( BaseClass t ) { } | Difference between a base class and a contitioned generic |
C# | I want to write extension methods for converting a vector and matrix into string . I did this in the following way.For VectorFor MatrixNow i am using following code which causes ambiguity.ErrorCan anyone suggest me to write these extension methods correctly.Thanks in advance . | public static string GetString < T > ( this T [ ] SourceMatrix , string ColumnDelimiter = `` `` ) { try { string result = `` '' ; for ( int i = 0 ; i < SourceMatrix.GetLength ( 0 ) ; i++ ) result += SourceMatrix [ i ] + ColumnDelimiter ; return result ; } catch ( Exception ee ) { return null ; } } public static string ... | How to write overloaded generic extension methods for T [ ] , T [ ] [ ] without ambiguity ? |
C# | I have an IEnumerable of actions and they are decendent ordered by the time they will consume when executing . Now i want all of them to be executed in parallel . Are there any better solutions than this one ? So my idea is to first execute all expensice tasks in terms of time they need to be done . EDIT : The question... | IEnumerable < WorkItem > workItemsOrderedByTime = myFactory.WorkItems.DecendentOrderedBy ( t = > t.ExecutionTime ) ; Parallel.ForEach ( workItemsOrderedByTime , t = > t.Execute ( ) , Environment.ProcessorCount ) ; | How to optimize Workqueue of well know time consuming processes |
C# | I 'm trying to understand async-await at a deep level . Whenever I see examples of how it works , the example uses an awaitable method called LongRunningTask or similar and in it is a Task.Delay or a new WebClient ( ) .Download ( `` http : //google.com '' ) or something similar . I 'm trying to figure out what would be... | var task = LongRunningTask ( ) ; DoSomething ( ) ; int x = DoSomethingElse ( ) ; int y = await task ; int z = x + y ; DoSomething ( ) ; int x = DoSomethingElse ( ) ; | What is a rigorous definition of what should be an `` awaitable '' task ? |
C# | I 'm running some code that only has to run once but it depends on external resources and may fail . I want the error to appear in the event log but I do not want the user to see it . I 'd like to avoid using custom error pages if possible.I could catch the exception and write it to the event log myself but I 'm concer... | public void Init ( HttpApplication context ) { try { throw new Exception ( `` test '' ) ; // This is where the code that errors would go } catch ( Exception ex ) { HttpContext.Current.Application.Add ( `` CompilationFailed '' , ex ) ; } } private void context_BeginRequest ( object sender , EventArgs e ) { if ( HttpCont... | Cleanest way to throw an error but not show the user that it has errored ( without custom error pages ) |
C# | I am trying to parse the string and see if the value after `` : '' is Integer . If it is not integer then remove `` Test : M '' from string . Here is the example string I have.The result I need testString = `` Test:34 '' | string testString = `` Test:34 , Test : M '' ; string [ ] data = testString.Split ( ' , ' ) ; for ( int i = 0 ; i < data.Length ; i++ ) { string [ ] data1 = data [ i ] .Split ( ' : ' ) ; int num = 0 ; if ( Int32.TryParse ( data1 [ 1 ] , out num ) ) { } } | Help with String parsing |
C# | I want to return a list of a certain entity grouped by a certain property , ordered descending by timestamp and paginated ( using Skip and Take ) . What I got is this : Upon execution I got the Exception : ... I called OrderBy ( ) ( albeit Descending ) and I called it before Skip ( ) ! What am I missing ? | container.CoinMessageSet.Where ( c = > c.MessageState ! = MessageStateType.Closed & & ( c.DonorOperator.OperatorCode.Equals ( `` opcode '' ) || c.RecipientOperator.OperatorCode.Equals ( `` opcode '' ) ) ) .OrderByDescending ( c = > c.TimeStamp ) .GroupBy ( c = > c.Reference ) .Skip ( x ) .Take ( 100 ) ; The method 'Ski... | Paginating a linq query which uses OrderBy |
C# | I have a class which I am using as a descriptor for an object . In that descriptor , there are several Type references for classes that are to be instantiated for different operations involving that object . I was thinking of pulling those references out and replacing them with attributes on the descriptor class.From t... | class MyDescriptor : BaseDescriptor { public Type Op1Type { get ; } public Type Op2Type { get ; } } [ Op1 ( typeof ( foo ) ) ] [ Op2 ( typeof ( bar ) ) ] class MyDescriptor : BaseDescriptor { } | Inelegant/improper use of attributes ? |
C# | If i do a query , ordering elements as below , i get ascending order.If i add the ascending keyword i get the same results.I recognise that adding the ascending keyword in the second example could increase readability as it removes the need to know the default order of orderby.Is there any other reason for the ascendin... | var i = from a in new int [ ] { 1 , 2 , 3 , 4 , 5 } orderby a select a ; var i = from a in new int [ ] { 1 , 2 , 3 , 4 , 5 } orderby a ascending select a ; | Does ascending keyword exist purely for clarity when used with orderby ? |
C# | I have created a grid layout . It displays 100 balls . Initially , all the balls will be in a random position . Every 25 ms a ball will move some unit ( this is common for all the balls ) in a random direction . You can see this in action in the below image : Even though the direction of the balls is random , after som... | Random random = new Random ( ) ; var direction = random.NextDouble ( ) * 360 ; var ballTranslate = child.RenderTransform.TransformPoint ( new Point ( 0 , 0 ) ) ; var x = ballTranslate.X ; var y = ballTranslate.Y ; var x1 = x + ( parm.Speed * Math.Cos ( direction ) ) ; while ( x1 < 0 || x1 > ( parm.CellSize * parm.NoOfS... | Why do these random events follow a specific pattern ? |
C# | I have the habit of breaking the rules if it makes my code more concise or my API more convenient to use , and if I can thoughtfully get away with doing so in the specific circumstances . I 'd like to know if I can get away with the following such infringement.The following illustration includes a single Child and sing... | public sealed class Child : INotifyPropertyChanged { private Child ( ) { //initialize basic state } public Child ( Parent parent ) : this ( ) //invoke parameterless contructor to initialize basic state { this.Parent = parent ; //the last thing before the public ctor exits } public Parent Parent { get { return parent ; ... | Hand off instance before constructor returns |
C# | ( The `` user-defined '' in the title refers to the fact that addition and subtraction of TimeSpan and DateTime are not a part of the C # standard . They are defined in the BCL . ) Playing around with lifted operators on nullable TimeSpan and DateTime values , I wrote the following code . Note that the framework offers... | static void Main ( ) { DateTime ? n_dt = new DateTime ( 2012 , 12 , 25 ) ; TimeSpan ? n_ts = TimeSpan.FromDays ( 62.0 ) ; var a = n_dt + n_ts ; // OK var b = n_ts + n_ts ; // OK var c = null + n_dt ; // OK , string concatenation ! Type of expression is String var d = null + n_ts ; // OK , compiler prefers TS+TS , not D... | Curious overload resolution when using a naked null literal with user-defined operators |
C# | I am using a ScintillaNET control in my C # Winforms application . I am trying to implement an auto-tag feature that will auto-complete the tag before , for example , when a user types < html > , auto-complete feature will trigger and insert < /html > . I 'm using the ScintillaNET CharAdded function for this implementa... | if ( caretPos ! = 0 ) { //If the characters before the caret are `` ml > '' ( last three chars from `` < html > '' ) if ( TextArea.Text [ caretPos - 1 ] == ' > ' & & TextArea.Text [ caretPos - 2 ] == ' l ' & & TextArea.Text [ caretPos - 3 ] == 'm ' ) { TextArea.Text = TextArea.Text.Insert ( caretPos , `` < /html > '' )... | How to prevent ScintillaNET control from auto scrolling ? |
C# | I am writing my code in C # and .NET Core 2.0.5 . When using a TypeConverter for the ushort-type , and a conversion fails , the FormatException-message refers to Int16 , rather than UInt16 . Can anyone explain this to me ? The other types I tested this with ( decimal , double , float , int , long , short , uint , ulong... | [ Fact ] public void FailingToConvertUShort_GivesFormatExceptionMessage_WithCorrectType ( ) { // Arrange var badvalue = `` badvalue '' ; var typeConverter = TypeDescriptor.GetConverter ( typeof ( ushort ) ) ; try { // Act var result = typeConverter.ConvertFrom ( context : null , culture : new CultureInfo ( `` en-GB '' ... | Why does the FormatException returned by a TypeConverter for an ushort-type refer to Int16 ? |
C# | Ok , let 's have some code : What precisely is going on behind the scenes that is causing the compiler to baulk ? The compiler is stopping me from modifying a member of the copy of the object I want to change . But why is a copy being made from this array ? A little more research throws up : Now , what do you think bad... | //I complie nicelyValueType [ ] good = new ValueType [ 1 ] ; good [ 0 ] .Name = `` Robin '' ; //I do n't compile : Can not modify expression because its not a variableIList < ValueType > bad = new ValueType [ 1 ] ; bad [ 0 ] .Name = `` Jerome '' ; struct ValueType { public string Name ; } //Adding to watch the followin... | IList < mutable_struct > vs mutable_struct [ ] |
C# | What is the difference between this two codes ? and Which method is preferd ? | class SomeClass { SomeType val = new SomeType ( ) ; } class SomeClass { SomeType val ; SomeClass ( ) { val = new SomeType ( ) ; } } | What is the difference between this initialization methods ? |
C# | I 'm doing a project using Visual Studio 2013 using C # . I want the timer to countdown from 120 minutes to 0 minutes and when it reaches 0 , a message box will show that the time is up . I also want the timer to reset when the reset button is pressed . However , when I pressed the reset button , even though the timer ... | private void startbutton_Click ( object sender , EventArgs e ) { timer.Enabled = true ; foreach ( var button in Controls.OfType < Button > ( ) ) { button.Click += button_Click ; timer.Start ( ) ; button.BackColor = Color.DeepSkyBlue ; } } private void stopandresetbutton_Click ( object sender , EventArgs e ) { button.Ba... | Timer and Buttons Issues |
C# | I have a series of methods ( with variable number of parameters ) that return a TaskI want to create a method that does something before and after each of this methods , by passing the Task.I 've simplified everything ( removed cancellationToken , actual processing , etc ) in this sample : And in my main : the console ... | public async Task < string > GetDataString ( ) { Console.WriteLine ( `` Executing '' ) ; return `` test '' ; } public async Task < T > Process < T > ( Task < T > task ) { Console.WriteLine ( `` Before '' ) ; var res = await task ; Console.WriteLine ( `` After '' ) ; return res ; } Task < string > task = GetDataString (... | Defer starting of a Task < T > |
C# | I 'm using the ? ? operator to try and assign an object based on the best match found in a list.I have various matching rules but have simplified this for the example : For debugging purposes , I would like to store a string logging which rule was the one which successfully assigned objectImTryingToSet as I have a bug ... | objectImTryingToSet =MyListOfPotentialMatches.FirstOrDefault ( */lamda checking numerous things*/ ) ? ? //rule1MyListOfPotentialMatches.FirstOrDefault ( */lamda checking different numerous things*/ ) ? ? //rule2MyListOfPotentialMatches.FirstOrDefault ( */lamda checking again different numerous things*/ ) ; //rule3 stri... | Capturing which left hand item in the null-coalescing operator successfully assigned variable |
C# | In this made up example purely for practice , here is what I want to return : If two students join a school within a specified period of time , say , 2 seconds , then I want a data structure returning both the students , the school they joined and the time interval between their joining.I have been thinking along these... | class Program { static void Main ( string [ ] args ) { ObserveStudentsJoiningWithin ( TimeSpan.FromSeconds ( 2 ) ) ; } static void ObserveStudentsJoiningWithin ( TimeSpan timeSpan ) { var school = new School ( `` School 1 '' ) ; var admissionObservable = Observable.FromEventPattern < StudentAdmittedEventArgs > ( school... | Is there an operator that works like Scan but let 's me return an IObservable < TResult > instead of IObservable < TSource > ? |
C# | I wanted to create a method extending IQueryable where a user can specify in a string a property name by which he wants to distinct a collection . I want to use a logic with a HashSet.I basically want to emulate this code : using expression trees.This is where i got so far : I get an exception when Expression.Block is ... | HashSet < TResult > set = new HashSet < TResult > ( ) ; foreach ( var item in source ) { var selectedValue = selector ( item ) ; if ( set.Add ( selectedValue ) ) yield return item ; } private Expression AssembleDistinctBlockExpression ( IQueryable queryable , string propertyName ) { var propInfo = queryable.ElementType... | Creating DistinctBy using Expression trees |
C# | Consider this interface : It compiles without errors or warnings.As discussed in this question , and mentioned in the Covariance and Contravariance FAQ : Variance is supported only if a type parameter is a reference type.So why does the above interface compile ? It would make sense to fail ( or at least warn ) on the `... | interface Test < out T > where T : struct { } typeof ( IDummy ) .IsAssignableFrom ( typeof ( MyStruct ) ) ; // should return truetypeof ( ITest < IDummy > ) .IsAssignableFrom ( typeof ( ITest < MyStruct > ) ) ; // returns false ITest < MyStruct > foo = ... ; var casted = ( ITest < IDummy > ) foo ; | Why does this covariance declaration compile ? |
C# | I have two interfaces . ICacheHolder is going to be implemented by a class implementing the logic of an game object and IVisualizer which is going to be the visual representation.Every ICacheHolder connects to one IVisualizer object the relation is 1 to 1.I 'm trying to determine if its better ( performance/memory wise... | public interface ICacheHolder { void updateCacheWithCurrentState ( int chachFrame ) ; void resizeCache ( int newSize ) ; T getCacheFrame < T > ( int cacheIndex , float interpolationToNext ) where T : struct ; } public interface IVisualizer { void updateVisualization ( ICacheHolder cacheHolder , int cacheIndex , float i... | Two Lists containing an interface versus one List containing a struct with two interfaces |
C# | I was working with a coworker on some basic C # tutorials and we came across what we though was an interesting conundrum.The following code works as expected : It gets the string array and prints out the string `` 1 , 2 , 3 '' to the console using the Console.WriteLine ( string format , params object [ ] arg ) overload... | string [ ] strings = { `` 1 '' , `` 2 '' , `` 3 '' } ; Console.WriteLine ( `` { 0 } , { 1 } , { 2 } '' , strings ) ; int [ ] ints = { 1 , 2 , 3 } ; Console.WriteLine ( `` { 0 } , { 1 } , { 2 } '' , ints ) ; int [ ] ints = { 1 , 2 , 3 } ; Console.WriteLine ( `` { 0 } , { 1 } , { 2 } '' , ints [ 0 ] , ints [ 1 ] , ints [... | int [ ] using `` wrong '' Console.WriteLine overload |
C# | I have the following class with some methods and I would like to use this as a base class of another class.I do n't want this class to be instantiated , but the derived class should still use the original implementation of the methods of its base class.Is it possible ? What should be my modifier ? | public class BaseClass { public string DoWork ( string str ) { // some codes ... } // other methods ... } | What would be the right modifier ? |
C# | I have a map with 2 Pushpins , when I load the page , I am setting the location of one of the pushpins in the code behind . However , when I try to reference the pin , it is null.XAMLC # Lat and Lon are definitely in the QueryString.Before this , used That works for the emulator , but not on the real phone.I have tried... | < maps : Map x : Name= '' mapEventLocation '' ZoomLevel= '' 15 '' Grid.Row= '' 1 '' Tap= '' mapEventLocation_Tap '' > < maptoolkit : MapExtensions.Children > < maptoolkit : Pushpin x : Name= '' userLocationPin '' Content= '' You '' Visibility= '' Collapsed '' / > < maptoolkit : Pushpin x : Name= '' eventLocationPin '' ... | Pushpin is null |
C# | I 'm passing a List of Custom Objects to my Custom Exception Class and need to display all the objects in the message . How can I do this ? The error tells me the type of object , but I need the serial number attribute that 's tied to each object in the list . | public class MissingUnitSNSException : Exception { public MissingUnitSNSException ( ) { } public MissingUnitSNSException ( List < UnitViewModel > missingsns ) : base ( String.Format ( `` Serial Numbers not found : { 0 } '' , missingsns ) ) { } } | How do I display a list of objects in an Exception ? |
C# | How can I read a very long string from text file , and then process it ( split into words ) ? I tried the StreamReader.ReadLine ( ) method , but I get an OutOfMemory exception . Apparently , my lines are extremely long.This is my code for reading file : And the code which splits line into words : | using ( var streamReader = File.OpenText ( _filePath ) ) { int lineNumber = 1 ; string currentString = String.Empty ; while ( ( currentString = streamReader.ReadLine ( ) ) ! = null ) { ProcessString ( currentString , lineNumber ) ; Console.WriteLine ( `` Line { 0 } '' , lineNumber ) ; lineNumber++ ; } } var wordPattern... | How to split a huge file into words ? |
C# | That 's very simple question I believe . Could anybody explain why this code outputs 1000 , not 1050 | public class Program { public static void Main ( ) { Bus b = new Bus ( 1000 ) ; ( ( Car ) b ) .IncreaseVolume ( 50 ) ; Console.WriteLine ( b.GetVolume ( ) ) ; } } public interface Car { int GetVolume ( ) ; void IncreaseVolume ( int amount ) ; } public struct Bus : Car { private int volume ; public Bus ( int volume ) { ... | Why does this value in the struct not change at all ? |
C# | Why does the first call to Foo below compile but the second one results in an ambiguous invocation compiler error ? ( using c # 7.2 ) If I remove the first ( Func < int > ) implementation of Foo , and hence the possibility of ambiguity , then the compiler ( correctly ) reports that Bar does n't have the correct signatu... | private static void AmbiguousAsyncOverload ( ) { Foo ( ( ) = > Bar ( ) ) ; // This is OK //Foo ( Bar ) ; // Error , ambiguous overload } private static void Foo ( Func < int > func ) { func ( ) ; } private static void Foo ( Func < string > func ) { func ( ) ; } private static int Bar ( ) { return 4 ; } | Why is this method invocation ambiguous ? |
C# | Should the Model , View or the Controller be the one that knows the page title ? Option 1Use the model to store the page title ( this makes the model more of a view-model ) : Then the view can simply set the title accordinglyOption 2The view knows its own title : and somewhere in view or the default layout its being us... | public class SomeModel { string Title { get ; set ; } } < title > @ Model.Title < /title > @ { ViewBag.Title = `` Some Title '' ; } < title > @ ViewBag.Title < /title > ViewBag.Title = `` Some Title '' < title > @ ViewBag.Title < /title > | Who should know about the page title in Asp.Net MVC ? |
C# | In a case like this , where my task could return instantly because of certain conditions : Is it correct return ; , should I use Task.FromResult ( false ) ; , or is there a more correct way ? | public async Task Test ( List < int > TestList ) { if ( TestList.Count ( ) == 0 ) return ; // Do something await UploadListAsync ( TestList ) ; } | .NET async/await : in this case should I return something ? |
C# | I 'm experiencing weird behavior when converting a number to a double , when using culture information.When converting `` 3,3 '' using the Dutch culture , is handled correctly . If I convert `` 3,3 '' using the US culture , it returns 33 . I was expecting an error . See my example : What is the correct way to handle th... | static void Main ( string [ ] args ) { CultureInfo cultureDutch = new CultureInfo ( `` nl-NL '' ) ; CultureInfo cultureUS = new CultureInfo ( `` en-US '' ) ; System.Threading.Thread.CurrentThread.CurrentCulture = cultureDutch ; Console.WriteLine ( `` Input 3,3 -- > Expected 3,3 '' ) ; Console.WriteLine ( `` Output = ``... | Number with decimal separator incorrectly cast to Double |
C# | I 'm having problems with calling a method that I have made.The method I 'm calling to is as folowsI 'm caling the method with the this code but I get an compiler error A ref or out argument must be an assignable variableDoes anyone else had this problem or am I just doing something wrong ? | public bool GetValue ( string column , out object result ) { result = null ; // values is a Dictionary < string , object > if ( this._values.ContainsKey ( column ) ) { result = Convert.ChangeType ( this._values [ column ] , result.GetType ( ) ) ; return true ; } return false ; } int age ; a.GetValue ( `` age '' , out a... | Trouble with out parameter |
C# | I have two properties with the same name and with a different case Title and TITLE : I 'm including Title in OData config : Here is action of OData controller : When I send https : //localhost:44326/Products ? $ select=Id , TITLE request , in queryOptions.ApplyTo ( products ) ; point I am getting following exception : ... | public class Product { [ Key ] public Guid Id { get ; set ; } public string Name { get ; set ; } public decimal Price { get ; set ; } public string Category { get ; set ; } [ NotMapped ] public virtual string Title { get ; set ; } public string TITLE { get ; set ; } } ODataModelBuilder builder = new ODataConventionMode... | AmbiguousMatchException while match case property in OData |
C# | I want to set the maxReceivedMessageSize in the App.config of the WCF Client . If the maxReceivedMessageSize equals or is smaller then 4215 it works fine . Though when setting it to 4216 or any value above it , the default value of 65536 is taken.My Client CodeAnd The relavant Server CodeAny idea how to fix this ? | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5 '' / > < /startup > < system.serviceModel > < bindings > < basicHttpBinding > < binding name= '' BasicHttpBinding_IConexaApiServic '' maxReceivedMessageSize= '' ... | WCF maxReceivedMessageSize cant set over 4215 |
C# | I have an Employee table in my database and a SQL table value function that return exactly same structure as my employee table . I 'm changing some fields value ( Like GroupNumber ) of table in my function . I imported the function in EF and set return type To Employee entity . Now I run the following query : The query... | IQueryable < Employee > employeeSearchResult = this.Context.EmployeeStateAtDate ( persianDate.ToDateTime ( ) ) ; var result = employeeSearchResult.Where ( q = > q.Group.Title.contains ( `` XYZ '' ) ) .Select ( q = > q.EmployeeN umber ) .ToList ( ) SELECT [ Filter1 ] . [ EmployeeNumber1 ] AS [ EmployeeNumber ] FROM ( SE... | Unnecessary join in Entity framework when using imported function ? |
C# | I have a piece of code that searches several third party APIs . I have the searches split into 2 groups based on the search criteria . I start both searches because each search is quite timely , but if the first group of searches results in an match I do n't want to wait around for the second search group to finish . S... | Dictionary < string , string > result = null ; NameSearchDelegate nameDel = new NameSearchDelegate ( SearchByName ) ; IAsyncResult nameTag = nameDel.BeginInvoke ( name , null , null ) ; if ( ! string.IsNullOrWhiteSpace ( telNum ) ) { result = SearchByTelNum ( telNum ) ; //Will return null if a match is not found } if (... | Is there anyway to end a delegate if I no longer care about the result ? |
C# | I try to figure out how I can access a static method within CallMe < T > ( ) of class DoSomething . Is reflection the only solution here ? I do not want to instantiate an object of type MyAction . Also if doing it through reflection is there a way to create the method through reflection within the method CallMe < T > (... | public class AskSomething { public void AskForSomething ( ) { DoSomething doSomething = new DoSomething ( ) ; doSomething.CallMe < MyAction > ( ) ; } } public class DoSomething { public void CallMe < T > ( ) { Type type = typeof ( T ) ; //Question : How can I access 'DoThis ( string text ) ' here ? //Most likely by ref... | Generic type passing and usage , can I do the following ? |
C# | Type checking for an Object takes place at compile time where as type checking for dynamic data type takes place at run time then how can we box a dynamic value into Object ? | dynamic dynamic = `` This is dynamic data type '' ; Object obj = dynamic ; Console.WriteLine ( obj ) ; | boxing on dynamic data type in c # ? |
C# | I know this is a truly weak example , but my question is more for understanding better programming practices , so please bear with me for the example itself.In working on a program , I have a situation where I have to replace multiple characters in a string with a single , different character . For example , all the ch... | string ChangedString1 = MyString.Replace ( `` `` , `` _ '' ) .Replace ( `` - '' , `` _ '' ) .Replace ( `` / '' , `` _ '' ) .Replace ( `` * '' , `` _ '' ) ; using System.Text.RegularExpressions ; ... string ChangedString2 = Regex.Replace ( MyString , @ '' [ \s-/* ] '' , `` _ '' ) ; | Cost of Referencing a library for just one use |
C# | I have the following XAML in my document : The image shows up fine in Win10 and Win8 , but in Win7 all I get is a red border with a transparent background and no image inside . When I use a static URL , like to the google logo , it renders in all versions.Anyone have any idea how I can make the image render in Windows ... | < Border HorizontalAlignment= '' Right '' VerticalAlignment= '' Bottom '' Height= '' 100 '' Width= '' 100 '' BorderBrush= '' Red '' BorderThickness= '' 2 '' > < Image x : Name= '' image '' Source= '' http : //myinternalserver/mywebservice/getimage.aspx ? id=1234 & amp ; ContentType=Image '' / > < /Border > | Image Renders in Win8/Win10 but not Win7 |
C# | Generally speaking , my dependencies are abstracted to interfaces , but I will only be using one concrete implementation during non-testing use . For example , were I to write a FooService : Now purists tend to gasp in horror , because I instantiated a concrete class in the parameterless constructor . I have , in the p... | public class FooService : IFooService { private readonly IBarDependency _barDependency ; public FooService ( IBarDependency barDependency ) { this._barDependency = barDependency ; } public FooService ( ) : this ( new BarDependency ( ) ) { // nothing to do here } . . . // code goes here } | Dependency Injection : what do you lose when instantiating concrete classes in parameterless constructor |
C# | I have noticed someone has done this in C # - notice the new ( ) What does this achieve ? | public class MyClass < T > where T : new ( ) { //etc } | What does generic typing to a new instance achieve ? |
C# | Usually play around with making games but I 'm taking a detour into making a little question and answer app , for educational purposes . Anyway I have a question class which holds numerous members : the question itself , the answer to the question , an array of possible answers etc . No doubts this should be a class . ... | public class Answer { public string Answer { get { return answer ; } private set { answer = value ; } } public Answer_Category = Some_Value ; // The enum . public int ID { get { return id ; } private set { return id ; } } private string answer ; private int id ; } | Make answer class a struct ? |
C# | Sometimes the result is 0 , sometimes the result is -xxxxxx . I do n't know why . Can anybody explain it and tell me the correct usage . | private const int Total = 500000 ; private static volatile int _count = 0 ; private static void Main ( ) { Task task = Task.Factory.StartNew ( Decrement ) ; for ( int i = 0 ; i < Total ; i++ ) { _count++ ; } task.Wait ( ) ; Console.WriteLine ( _count ) ; Console.ReadLine ( ) ; } private static void Decrement ( ) { for ... | Why does using volatile produce a different result ? |
C# | In F # , if you are interoperating with another .NET language , or if you using the AllowNullLiteral attribute , a reference type can be null . The example that comes to mind right away are strings : But with C # 8 and dotnet core 3 , we can opt in to Nullable Reference Types . I would have to write the above code in C... | let str : string = null string ? str = null ; let str : string = null // error can not do thislet str : string ? = null let str : string = nulllet strOpt = Option.ofObj str | Using Nullable Reference Types in F # |
C# | I 'm not looking for answers telling me there is an easier way of doing this , just treat it as a thought experiment . First up , am I right in thinking that this is three loops ? Where ( ) , ToList ( ) and ForEach ( ) ? Second of all , ( assuming it is three loops ) am I right in thinking this is n to the power of 3 i... | collection.Where ( i = > i.condition ) .ToList ( ) .ForEach ( i = > SomeComplicatedOpInvolving_i ) ; | Am I right in thinking this snippet is O ( n^3 ) ? |
C# | I 've recently become involved ( or rather , re-involved ) in a web project I originally wrote in 2000 in ASP . Over the last 13 years , the project has evolved and become quite convoluted both in the technology uses ( ASP , ASP.NET 1.1 , ASP.NET 3.5 and ASP.NET 4.0 ) . We are now working in VS 2010.There are multiple ... | < ItemGroup > < Content Include= '' ..\..\Core\XXXXX.XXXXX.ASP.Web\Images\**\* . * '' > < CopyToOutputDirectory > Always < /CopyToOutputDirectory > < Link > images\ % ( RecursiveDir ) % ( FileName ) % ( Extension ) < /Link > < /Content > < /ItemGroup > | How do I make linked images in my web project appear on my local dev web server ? |
C# | I want to covert a big number , which is bigger than int32 maximum range - to int32 using C # . So that if it is over than maximum range 2147483647 , then it will start again from -2147483648 . For now I am doing this like : I am not sure that if I doing this correctly . Is there any utility function or quick way to do... | long val = 3903086636L ; long rem = val % 2147483648L ; long div = val / 2147483648L ; int result = div % 2 == 0 ? ( int ) rem - 1 : -2147483648 + ( int ) rem ; | Convert Int32.Maximum+ valued number to int32 |
C# | I like to check that all the parameters of the method have the correct information before doing something with them . Something like this : However , in this post someone comments that it is not a good idea to throw an exception as normal flow , but I am not sure if this is the case or not , because if I have to check ... | public method ( MyType param1 ) { try { if ( param1 == null ) { throw new ArgumentNullException ( `` Error1 '' ) ; } if ( param1.Property1 == null ) { throw new ArgumentNullException ( `` Error2 '' ) ; } if ( param1.Property1.Amount < = 0 ) { throw new ArgumentException ( `` Error3 '' ) ; } ... //Do what I need with th... | throw exceptions or not when check the parameters of a method ? |
C# | There is a list of binary values : my algorithm aims to convert any false item to true , if they are adjacent to a true value : My solution works , as you will see . I can do it through two different loops , and then zip two lists : However , it does n't seem to be the best solution since the problem looks very easy . ... | List < bool > myList = new List < bool > ( ) { true , true , false , false , true , false , false , false , true , true , true , false , false } ; result = { true , true , true , true , true , true , false , true , true , true , true , true , false } List < bool > firstList = new List < bool > ( ) ; List < bool > secon... | Infecting\transmitting value to the adjacent items of list , in C # |
C# | If I have two classes , A and B where B derives from A : I can upcast quite happily an instance of B to A.Now , I can understand how the runtime can determine that the underlying type is B , as page 132 of the ECMA-335 ( Common Language Infrastructure ( CLI ) Partitions I to VI ) states Objects of instantiated types sh... | class A { } class B : A { } B b = new B ( ) ; A a = b ; | Information on Casted C # Reference Types in Memory |
C# | -- -- -- Please jump to the last update -- -- -- -- -- -I have found a bug ( in my code ) and I am struggling to find correct understanding of it.It all boils down to this specific example taken from the immediate window while debugging : x and dx are both of type float . So why is the boolean value different when I do... | x0.00023569075dx-0.000235702712x+dx+1f < 1ftrue ( float ) ( x+dx+1f ) < 1ffalse x+=dxif ( x+1f < 1f ) // Add a one to truncate really small negative values ( originally testing x < 0 ) { // do actions accordingly // Later doing x+=1 ; // Where x < 1 has to be true , therefore we have to get rid of really small negative... | Why does this cast change the result when even VS says it is redundant ? |
C# | Recently while doing some work with C # & ActiveMQ ( via the Apache.NMS libraryies ) I came across the following property on the ActiveMQBytesMessageThe InitialiseReading method handled the connection & streaming of the data from active MQ into the .dataIn field . The problem though was that IT DID THIS EVERYTIME . And... | public new byte [ ] Content { get { byte [ ] buffer = ( byte [ ] ) null ; this.InitializeReading ( ) ; if ( this.length ! = 0 ) { buffer = new byte [ this.length ] ; this.dataIn.Read ( buffer , 0 , buffer.Length ) ; } return buffer ; } .. ( setter omitted ) } byte [ ] myBytes = new byte [ msg.Content.Length ] ; //Touch... | Are `` One Shot '' Property Getters considered an acceptable coding standard in .NET ( or in general ) |
C# | I am a bit unclear on the syntax of inheritance for interfaces in C # .For example : What is the difference between this : and this : Or , for a real world example , Why is ICollection < T > declared like this : instead of this : given that IEnumerable < T > already inherits from IEnumerable ? | public interface IFoo { } public interface IBar : IFoo { } public interface IQux : IBar { } public interface IQux : IBar , IFoo { } public interface ICollection < T > : IEnumerable < T > , IEnumerable public interface ICollection < T > : IEnumerable < T > | Declaring interface inheritance in C # |
C# | This works as expected : While this throws an InvalidCastException : Why does the cast fail from an object when the underlying type is still byte ? | byte b = 7 ; var i = ( int ) b ; byte b = 7 ; object o = b ; var i = ( int ) o ; | Why does this typecast cause an error ? |
C# | Is there a way to get the type of an interface that a class implements . For further explanation of the problem here 's what I mean . For example : I need to fill the commented area . Thanks in advance for your help , community ! | public interface ISomeInterface { } public class SomeClass : ISomeInterface { } public class SecondClass { ISomeInterface someclass ; public SecondClass ( ) { someclass = new SomeClass ( ) ; } public Type GetInterfaceInSomeWay ( ) { //some code } } | Return the types of interfaces that a class implements C # |
C# | I have a stored procedure which takes about 5-8 mins to execute.The user just sees a message `` Please wait while report is being generated '' It is very likely that people may think that it has stopped working ... or something went wrong.. etc..Is there any way a stored procedure can keep returning status while execut... | { logical block 1 } logical block 1 completed ! { logical block 2 } logical block 2 completed ! { logical block 3 } logical block 3 completed ! | Very lengthy stored procedure status |
C# | I 'm browsing through the EF7 code on Github and found a line that looks like this : I have seen that syntax before on a class level , like this : Which says that T should be of type class . But the line from the EF7 source confuses me . I 'm not sure what it does . | public virtual DbSet < TEntity > Set < TEntity > ( ) where TEntity : class = > _setInitializer.Value.CreateSet < TEntity > ( this ) ; public class SomeClass < T > where T : class | What does `` Property where class = > someFunction '' mean in C # |
C# | I 'm working on a small app on .NET , I need to point the same data with 2 diferent lists , I 'm wondering if perhaps the memory is duplicated , for exampleI guess that .NET as Java will not duplicate the object Person , so it will be keeped , so if I do this : Will change the object in both lists . Is it right ? Thank... | public class Person { public string name ; public int age ; ... . public Person ( name , age ) { this.name = name ; this.age = age ; } } SortedList < string > names ; SortedList < int > ages ; Person person1 = new Person ( `` juan '' ,23 ) ; names.add ( `` juan '' , person1 ) ; ages.add ( 23 , person1 ) ; names ( `` ju... | Duplicated Memory on .NET using two lists |
C# | I created a windows service project . And if you create a new project you get something like this : And now I have to add some functions and timer to my class Service1 ( ) and then everything is fine . Now let say , my service should do some stuff like : reading some files , deleting some folders , checking connections... | ServiceBase [ ] ServicesToRun ; ServicesToRun = new ServiceBase [ ] { new Service1 ( ) } ; ServiceBase.Run ( ServicesToRun ) ; ServicesToRun = new ServiceBase [ ] { new Service1 ( ) , new Service2 ( ) //not sure this will compile } ; | Should I use only one new service ( ) or more ? |
C# | Is there a better alternative to the try catch madness in the code below ? I 'm collecting all kinds of similar system information and have several more of these annoying try catch constructions and would very much like to get rid of them.Note that this actually makes sense . Not all the process information in the try ... | foreach ( Process proc in Process.GetProcesses ( ) ) { try { Append ( proc.Threads.Count ) ; } catch { } try { Append ( proc.Id ) ; } catch { } try { Append ( proc.ProcessName ) ; } catch { } try { Append ( proc.BasePriority ) ; } catch { } try { Append ( proc.StartTime ) ; } catch { } Append ( proc.HandleCount , proc.... | Better alternative to Try Catch madness ? |
C# | BackgroundI 'm using StackExchange.Precompilation to implement aspect-oriented programming in C # . See my repository on GitHub.The basic idea is that client code will be able to place custom attributes on members , and the precompiler will perform syntax transformations on any members with those attributes . A simple ... | if ( Object.Equals ( p , null ) ) throw new ArgumentNullException ( nameof ( p ) ) ; public class TestClass { public void ShouldCreateDiagnostic ( [ NonNull ] int n ) { } } using System.Collections.Generic ; using System.Linq ; using Microsoft.CodeAnalysis ; using Microsoft.CodeAnalysis.CSharp ; using Microsoft.CodeAna... | StackExchange.Precompilation - How can I unit test precompilation diagnostics ? |
C# | I 'm a very new C # programmer , less than ~24 actual hours of raw typing/programming . I 'd say about a week however of reading , watching , and trying to understand things.Here 's the source code to my first program : The program does exactly what I want it to . The user types the bug check code they 're getting , it... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Bugcheck { class Program { static void Main ( string [ ] args ) { // Initializing variables string bugcheckExit = `` exit '' ; var message = `` '' ; var afterMessage = `` Type another bug c... | Fixing future problematic code ? |
C# | In my ASP.NET application I use code from here to find the build date of the application as UTC . The UTC value read from the assembly file is then formatted as follows : Now one user opens the page served by that application and seesand notifies the other user who opens the same page and seesBoth requests are served b... | //DateTime time return time.ToString ( `` dd MMM yyyy HH : mm : ss '' ) ; 28 сен 2012 04:13:56 27 Sep 2012 12:14:32 | Why would the same DateTime value yield different displayed time for different users ? |
C# | I have been playing out of boredom with retrieving random articles from wiki all at the same time . First I wrote this code : But I wanted to get rid of this async anonymous method : Task.Run ( async ( ) = > ... , so I replaced relevant part of code to this : I expected it to perform exactly the same , because the asyn... | private async void Window_Loaded ( object sender , RoutedEventArgs e ) { await DownloadAsync ( ) ; } private async Task DownloadAsync ( ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; var tasks = new List < Task > ( ) ; var result = new List < string > ( ) ; for ( int index = 0 ; index < 60 ; index++ ) { var task... | Why is synchronous code inside asynchronously awaited Task much slower than asynchronous code |
C# | I have to work through a large file ( several MB ) and remove comments from it that are marked by a time . An example : After filtering , I would like it to look like this : The nicest way to do it should be easing a Regex : Now this works perfectly for my purposes , but it 's a bit slow.. I 'm assuming this is because... | blablabla 12:10:40 I want to remove thisblablabla some moreeven more bla blablablablablabla some moreeven more bla Dataout = Regex.Replace ( Datain , `` [ 012 ] [ 0123456789 ] : [ 012345 ] [ 0123456789 ] : [ 012345 ] [ 0123456789 ] . * '' , string.Empty , RegexOptions.Compiled ) ; Dataout = Regex.Replace ( Datain , `` ... | Bad Regex performance while searching for times ( xx : xx : xx ) |
C# | This might be a stupid question , or oversight on my part , but..If you type 'method ' inside an attribute definition , as below : Visual Studio highlights the keyword . It does n't seem to highlight it outside of an attribute as far as I can tell , and hitting F1 in VS boots you to a 404.I 've never seen this actually... | [ method : ] public class MyClass | What is the method keyword used for in C # ? |
C# | My question is kind of related to this question but a bit more specific.I have a domain object Customer that looks like this : and Identity looks like this : Now based on the value of IsOrganization some logic within Identity needs to change , specifically if IsOrganization is true the Individual related fields ( first... | public class Customer : Party { public Identity Identity { get ; protected set ; } public bool IsOrganization { get ; set ; } } public class Identity : PersistableModel { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string MiddleInitial { get ; set ; } public string Title { get ... | How can I create an instance of a derived class from an instance of a base class and include private fields ? |
C# | I 'm using the hl7-dotnetcore package to create new HL7 messages . After creating them I want to serialize some of them to strings and some of them to bytes . I created an empty .NET Core console project with the following snippetUnfortunately I get two exceptions with '' Failed to validate the message with error - No ... | internal class Program { private static void Main ( string [ ] args ) { Message mdmMessage = new Message ( ) ; mdmMessage.AddSegmentMSH ( `` sendingApplication '' , `` sendingFacility '' , `` receivingApplication '' , `` receivingFacility '' , string.Empty , `` MDM^T02 '' , $ '' Id { DateTime.Now.Ticks } '' , `` P '' ,... | message validation throws `` No Message Found '' exception |
C# | I was thinking if without writing an ExpressionVisitor it 's possible to solve this issue the only point that I ca n't figure out is how to convert the invocation expression to the return type . if I set the return type to dynamic then it looks fine , but I wonder if there is better option to do that | Expression < Func < int , int , int > > multiply = ( n1 , n2 ) = > n1 * n2 ; Expression < Func < int , Expression < Func < int , int , int > > , Expression < Func < int , int > > > > power2 = ( adad , tabe ) = > Expression.Invoke ( tabe , Expression.Constant ( adad ) , Expression.Constant ( adad ) ) ; power2.Compile ( ... | wrap a linq expression with another linq expression |
C# | Could you explain me what does word `` property : '' mean ? | [ property : NotifyParentProperty ( true ) ] public string Filename { get ; set ; } | What is word `` property : '' in Attribute |
C# | I am in the process of refactoring a rather large portion of spaghetti code . In a nutshell it is a big `` God-like '' class that branches into two different processes depending in some condition . Both processes are lengthy and have lots of duplicated code.So my first effort has been to extract those two processes int... | public class ExportProcess { public ExportClass ( IExportDataProvider dataProvider , IExporterFactory exporterFactory ) { _dataProvider = dataProvider ; _exporterFactory = exporterFactory ; } public void DoExport ( SomeDataStructure someDataStructure ) { _dataProvider.Load ( someDataStructure.Id ) ; var exporter = _exp... | Is it a good design option to call a class ' initializing method within a factory before injecting it |
C# | When I do this : The value of currentPage is null.But the same logic , when I assign the increment value to an integer variable , and then try to get the currentPagecurrentPage gets populated.Does anyone have a good answer as to why one works and the other does n't ? | currentPage = metadataResponse.ApplicationType.Pages.Find ( page = > page.SortOrder == ++currentPage.SortOrder ) ; int sortOrder = ++currentPage.SortOrder ; currentPage = metadataResponse.ApplicationType.Pages.Find ( page = > page.SortOrder == sortOrder ) ; | Discrepancy in C # LINQ results |
C# | I have requirement to dynamically add property values based on column values . Current I am creating object as below : But I need to check if IMEI column is available or not in DataReader but when I am using if else then its giving syntax error I want to add IMEI if its available in DataReader how can I achieve that ? | while ( rd.Read ( ) ) { list.Add ( new DeviceModelInfo ( ) { ID = rd.GetGuid ( `` ID '' ) , Manufacturer = new Manufacturer ( ) { ID = rd.GetGuid ( `` ManufacturerID '' ) , Name = rd.GetString ( `` ManufacturerName '' ) , ManufacturerType ( ManufacturerEnum ) rd.GetInt32 ( `` ManufecturerType '' ) } , Model = rd.GetStr... | If/Else in Inline Synatx to declase class object with properties C # |
C# | I have a legacy ASP.NET 4.0 Webforms application that 's been in production for a while . I 'm now adding additional functionality in the form of a WebAPI REST service to it.Adding the WebAPI NuGet packages also added an entry into my web.config configuring the NewtonSoft.Json package runtime version : Now , since I ha... | < runtime configSource= '' runtime.config '' / > protected void Application_Start ( object sender , EventArgs e ) { ... // Route # 1 GlobalConfiguration.Configuration.Routes.MapHttpRoute ( `` Route1 '' , `` test/ { list } / { check } '' , new { Controller = `` Devices '' } ) ; ... } | Behavior different when `` externalizing '' certain config settings into external files |
C# | I have the following code using regex that hangs at the last line when I run it : It works fine if I remove one of the final backslashes in test , e.g.Can someone please help me figure out why it 's hanging ? I know I can set a timeout ; that 's not my question . | const char PathSeparator = '\\ ' ; const string PathPrefix = `` \\\\ '' ; var reg = new Regex ( string.Format ( `` ^ { 0 } ( ( [ ^ { 1 } \r\n\v\f\u2028\u2029 ] + ) { 1 } ? ) + $ '' , Regex.Escape ( PathPrefix ) , Regex.Escape ( PathSeparator.ToString ( ) ) ) ) ; var test = @ '' \\Inbox\Test123\Intermediate\3322FB69-FE3... | Why is this regex hanging with two trailing back-slashes but works fine with just one ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.