lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | In C # 7.2 , are readonly structs always passed to functions as if the `` in '' parameter is present ? If not , in what case would it be useful to copy the memory given that it 's readonly ? I have a readonly struct : So would there be a performance difference between these two methods when called billions of times : A... | public readonly struct Vec2 { public readonly double X ; public readonly double Y ; } public double Magnitude1 ( Vec2 v ) { return Math.Sqrt ( v.X*v.X + v.Y*v.Y ) ; } public double Magnitude2 ( in Vec2 v ) { return Math.Sqrt ( v.X*v.X + v.Y*v.Y ) ; } | Is it necessary to use the `` in '' modifier with a readonly struct ? |
C# | I recently wrote this and was surprised that it compiles : If I use this class as follows , I get an `` Ambiguous constructor reference '' and an `` Ambiguous invocation '' if I call Add.Obviously , there 's no ambiguity when I use int and double as generic types , except of course when I use both ints , which would al... | public class MyGeneric < U , V > { MyGeneric ( U u ) { ... } MyGeneric ( V v ) { ... } public void Add ( U u , V v ) { ... } public void Add ( V v , U u ) { ... } } var myVar = new MyGeneric < int , int > ( new MyIntComparer ( ) ) ; var myVar = new MyGeneric < int , double > ( new MyIntComparer ( ) ) ; myVar.Add ( 3 , ... | Generics in C # with multiple generic types leads to allowed and disallowed ambiguity |
C# | I 'm developing a class library which should be licensed to specific developer computers . There are no components so that the design time licensing checks ca n't be done . This check is in fact unavailable for pure class libraries : One has suggested to use Debugger.IsAttached to check if the lib is used on the develo... | if ( LicenseContext.UsageMode == LicenseUsageMode.Designtime ) ... | execute method from referenced class library before build .NET application for license checking |
C# | just messing around with the unsafe side of c # Is it possible to assign a string literal to a char pointer just like in C or do I have to do it as in the above snippet ? | unsafe { char* m = stackalloc char [ 3+1 ] ; m [ 0 ] = ' A ' ; m [ 1 ] = ' B ' ; m [ 2 ] = ' C ' ; m [ 3 ] = '\0 ' ; for ( char* c = m ; *c ! = '\0 ' ; c++ ) { Console.WriteLine ( *c ) ; } Console.ReadLine ( ) ; } | Assign a string literal to a char* |
C# | I have the following -Problem being that the value of i passed into ProcessResult seems to be the value when it starts , not the value of the iteration when it is created.What is the best way to protect against this ? | for ( int i = 0 ; i < N ; ++i ) { var firstTask = DoSomething ( ... ) ; var task = anotherTask.ContinueWith ( ( t ) = > ProcessResult ( i , t.Result ) ) ; } | Using anonymous methods inside of a delayed task inside of a loop |
C# | I 'm using Microsoft 's Entity Framework as an ORM and am wondering how to solve the following problem.I want to get a number of Product objects from the Products collection where the Product.StartDate is greater than today . ( This is a simplified version of the whole problem . ) I currently use : When this is execute... | var query = dbContext.Products.Where ( p = > p.StartDate > DateTime.Now ) ; SELECT * FROM Product WHERE StartDate > ( GetDate ( ) ) ; private Func < Product , bool > GetFilter ( ) { Func < Product , bool > filter = p = > p.StartDate > DateTime.Now ; return filter ; } var query = dbContext.Products.Where ( GetFilter ( )... | Why does EntityFramework 's LINQ parser handle an externally defined predicate differently ? |
C# | I 'm trying to convert this long JS regex to C # .The JS code below gives 29 items in an array starting from [ `` '' , '' 常 '' , '' '' , '' に '' , '' '' , '' 最新 '' , '' 、 '' , '' 最高 '' ... ] But the C # code below gives a non-splitted single item in string [ ] .Many questions in Stack Overflow are covering relatively s... | var keywords = / ( \ & nbsp ; | [ a-zA-Z0-9 ] +\ . [ a-z ] { 2 , } | [ 一-龠々〆ヵヶゝ ] +| [ ぁ-んゝ ] +| [ ァ-ヴー ] +| [ a-zA-Z0-9 ] +| [ a-zA-Z0-9 ] + ) /g ; var source = '常に最新、最高のモバイル。Androidを開発した同じチームから。 ' ; var result = source.split ( keywords ) ; var keywords = @ '' / ( \ & nbsp ; | [ a-zA-Z0-9 ] +\ . [ a-z ] { 2 , } | [ 一-... | C # Regex.Split is working differently than JavaScript |
C# | Just curious , is changing the size of a struct/value type a breaking change in C # ? Structs tend to be more sensitive in terms of memory layout since altering them directly affects the size of arrays/other structs . Are there any examples of code that breaks , either binary-wise or source-wise , after the layout of a... | // My.Library v1public struct MyStruct { } // My.Library v2public struct MyStruct { int _field ; } // App codeusing My.Library ; using System.Runtime.InteropServices ; Console.WriteLine ( Marshal.SizeOf < MyStruct > ( ) ) ; // before printed 1 , now prints 4 | Is changing the size of a struct a breaking change in C # ? |
C# | I have a string : Apple1231|C : \asfae\drqw\qwer|2342|1.txtI have the following code : What I want to be able to do is replace every | after the first | with \So i want to write out Apple1231|C : \asfae\drqw\qwer\2342\1.txt | Regex line2parse = Regex.Match ( line , @ '' ( \| ) ( \| ) ( \| ) ( \d ) '' ) ; if ( line2parse < 2 ) { File.AppendAllText ( workingdirform2 + `` configuration.txt '' , | C # Regex replace help |
C# | I have the following statement : I want to check and see if card.Details is null or empty ... if not , write the value . Is there any syntax that allows me to leave out the else conditional ? | serverCard.Details = ! String.IsNullOrEmpty ( card.Details ) ? card.Details : serverCard.Details ; | How to simplify this C # if/else syntax |
C# | I 've read a fair amount of posts on the subject , and I think I finally understand how the volatile keyword works in C # . Still I wanted to ask here just to make sure I understand the concepts properly . Consider the following code : From what I understand , if another thread were to set Enabled=false , the original ... | class ThreadWrapper { public bool Enabled { get ; set ; } private void ThreadMethod ( ) { while ( Enabled ) { // ... Do work } } } public bool Enabled { get { return mEnabled ; } set { mEnabled=value ; } } private volatile bool mEnabled ; class C { private volatile int i ; private volatile bool enabledA ; private volat... | Using volatile for one-way communication between threads in .NET |
C# | I have been looking in to you some code was n't working . Everything looks fine except for the following line.Before that line is executed Transport is null . I see the GetMock executed and that it returns a non null object . After that line Transport is still null ; I looked at the IL that was generated an it looks fi... | Transport = Transport ? ? MockITransportUtil.GetMock ( true ) ; IL_0002 : ldarg.0 IL_0003 : ldfld class [ Moq ] Moq.Mock ` 1 < class [ CommLibNet ] CommLibNET.ITransport > Curex.Services.Common.UnitTests.Messaging.TestIGuaranteedSubscriptionBase : :Transport IL_0008 : dup IL_0009 : brtrue.s IL_0012 IL_000b : pop IL_000... | Is the JIT generating the wrong code |
C# | I have an abstract class called EntityTypeTransform with a single abstract method designed to hold a Func delegate that converts an IDataRecord into an instance of T.An implementation of that class might look like ( does look like ) this : Now I want to keep an instance of each of these classes in a generic Dictionary ... | public abstract class EntityTypeTransform < TEntityType > where TEntityType : class { public abstract Func < IDataRecord , TEntityType > GetDataTransform ( ) ; } public class TaskParameterEntityTypeTransform : EntityTypeTransform < TaskParameter > { public override Func < IDataRecord , TaskParameter > GetDataTransform ... | Keep a Dictionary < Type , MyClass < T > > where elements are referenceable by type |
C# | Is there a make_tuple equivalent for C # /.NET ? I want to do something like thisC # seems to support it when i create my own functionBut msdn tuple shows not using itIs there or is n't there ? I can use 4.5 | mylist.Add ( new Tuple < string , int > ( `` '' , 1 ) ) ; Tuple < T , U > make_tuple < T , U > ( T t , U u ) { return new Tuple < T , U > ( t , u ) ; } ... var a = make_tuple ( 1 , `` '' ) ; //compiles ! Tuple < string , Nullable < int > > [ ] scores = { new Tuple < string , Nullable < int > > ( `` Jack '' , 78 ) , new... | Is there a make_tuple for C # ? |
C# | I have this string : '' B82V16814133260 '' what would be the most efficient way to get two strings out of it : left part String : `` B82V '' rigth part string : `` 16814133260 '' The rule is this : take all numbers on the right side and create string out of them , then take the reminder and place it into another string... | String leftString = `` '' ; String rightString= '' '' ; foreach ( char A in textBox13.Text.Reverse ( ) ) { if ( Char.IsNumber ( A ) ) { rightString += A ; } else { break ; } } char [ ] arr = rightString.ToArray ( ) ; Array.Reverse ( arr ) ; rightString=new string ( arr ) ; leftString = textBox13.Text.Replace ( rightStr... | the most efficient way to separate string |
C# | String interpolation is great and snippets are great , but they do n't play nice together . I have a snippet that looks ( in part ) like this : The locationfield part is supposed to be the replacement , but of course it will see as ' '' { e [ `` being a replacement . So when you try to use the snippet , that part is me... | job.Location = $ '' { e [ `` $ locationfield $ '' ] } '' ; return true ; job.Location = locationfield | How to escape string interpolation in snippet |
C# | Here 's a simple application that prints the method signature of a MethodCallExpression : I would expect the program to print out : But it instead prints out : When getting the Method property for the inherited MethodCallExpression , it always returns As MethodInfo ( the root class ) .However , in Visual Studio and I `... | using System ; using System.Linq ; using System.Linq.Expressions ; class A { public virtual void Foo ( ) { } } class B : A { public override void Foo ( ) { } } class C : B { public override void Foo ( ) { } } class Program { static void Main ( string [ ] args ) { PrintMethod < A > ( a = > a.Foo ( ) ) ; PrintMethod < B ... | MethodCallExpression.Method always returns the root base class 's MethodInfo |
C# | I noticed most of the developers are using event for callback and I 'm not sure whether I 'm doing in a right way.I noticed most of developers ' codes look like this : While the way I do `` event '' look like this : I hope someone could explain to me what 's the differences between both codes ? Which way of doing deleg... | public delegate void SampleDelegate ( ) ; public static event SampleDelegate SampleEvent ; public delegate void SampleDelegate ( ) ; public SampleDelegate SampleEvent ; // notice that I did n't set to static and not an event type | Which is the correct/better way of Delegate declaration |
C# | I 'm trying to insert some data into my DB ( Microsoft SQL Server ) My connection does not open and I get this message : Can not open database \ '' [ Sales and Inventory System ] \ '' requested by the login . The login failed.\r\nLogin failed for user 'Mostafa-PC\Mostafa'.here is my code : I 've done everything and I '... | public void InsertProduct ( List < string > _myName , List < int > _myAmount , List < int > _myPrice , string _date ) { string connectionString = @ '' Data Source=MOSTAFA-PC ; Initial Catalog= [ Sales and Inventory System ] ; Integrated Security=True '' ; string query = @ '' INSERT INTO dbo.product ( Name , Amount , Pr... | can not open database - requested by the login - why ca n't I connect to my DB ? |
C# | The following code is very repetitive : However , my attempt to use generics does not compile : The error message is as follows : Error 2 Operator '- ' can not be applied to operands of type 'T ' and 'T ' C : \Git ... \LinearInterpolator.cs How should I reuse my code ? Edit : fast runtime is important for this modules ... | public static double Interpolate ( double x1 , double y1 , double x2 , double y2 , double x ) { return y1 + ( x - x1 ) * ( y2 - y1 ) / ( x2 - x1 ) ; } public static decimal Interpolate ( decimal x1 , decimal y1 , decimal x2 , decimal y2 , decimal x ) { return y1 + ( x - x1 ) * ( y2 - y1 ) / ( x2 - x1 ) ; } public stati... | How to use generics to develop code that works for doubles and decimals |
C# | Could someone explain to me why this piece of code is doing well when I execute it on a x86 platform and why it fail on x64 ? Results : x86 Debug : 12345678910x64 Debug : 12345678910x86 Release : 12345678910x64 Release : 1111111111If I change something , like removing one of the unused variables , or if I remove the us... | class Program { static void Main ( string [ ] args ) { Test ( null , null , null , 0 , 1 ) ; } public static void Test ( List < string > liste , List < string > unused1 , string unused2 , int unused3 , long p_lFirstId ) { liste = new List < string > ( ) ; StringBuilder sbSql = new StringBuilder ( ) ; for ( int i = 0 ; ... | Variable is not incrementing in C # Release x64 |
C# | Everybody knows that asynchrony gives you `` better throughput '' , `` scalability '' , and more efficient in terms of resources consumption . I also thought this ( simplistic ) way before doing an experiment below . It basically tells that if we take into account all the overhead for asynchronous code and compare it a... | [ HttpGet ] [ Route ( `` async '' ) ] public async Task < string > AsyncTest ( ) { await Task.Delay ( _delayMs ) ; return `` ok '' ; } [ HttpGet ] [ Route ( `` sync '' ) ] public string SyncTest ( ) { Thread.Sleep ( _delayMs ) ; return `` ok '' ; } | Does asynchronous model really give benefits in throughput against properly configured synchronous ? |
C# | I have a Window with few controls on it . One of them is a DataGrid . I want to implement some non-default focus traversal . Namely : DataGrid is a single stop as a whole , not each row.When DataGrid is focused , user can navigate through rows using up and down keys.Navigating through columns using left and right keys ... | < DataGrid x : Name= '' DocumentTemplatesGrid '' Grid.Row= '' 2 '' ItemsSource= '' { Binding Source= { StaticResource DocumentTemplatesView } } '' IsReadOnly= '' True '' AutoGenerateColumns= '' False '' SelectionUnit= '' FullRow '' SelectionMode= '' Single '' TabIndex= '' 1 '' IsTabStop= '' True '' > < DataGrid.CellSty... | How to make DataGrid a single stop as a whole on focus traversal with arrow keys row selection ? |
C# | I 'm creating project in ASP.NET ( Framework 4.0 ) . I have used Asp LinkButton in Master Page & it has 2 page linked with it ( Home.aspx & service.aspx ) .Question As follows : That LinkButton1 works on Home.aspx and does n't work on service.aspx.User.master code as followUser.master.cs code for LinkButton1 ClickWhile... | < ul class= '' nav navbar-nav navbar-right '' > < li > < asp : LinkButton ID= '' LinkButton1 '' runat= '' server '' onclick= '' LinkButton1_Click '' AutoPostBack= '' true '' > Signout < i class= '' glyphicon glyphicon-off '' > < /i > < /asp : LinkButton > < /li > < li class= '' dropdown '' > < a href= '' # '' class= ''... | LinkButton on Master Page does n't fire on Second Child Page in ASP.NET |
C# | How to document the classes & properties & functions that are generated automatically using LINQ to SQL DBML ? I managed to provide documentation to the datacontext class by defining the same partial class in another file with < summary > so it wo n't be removed if the DBML got refreshed This would work for table mappi... | /// < summary > /// Linq to SQL datacontext /// < /summary > public partial class LinqDBDataContext { } -- ============================================= -- Author : < Katia Aleid > -- Create date : < 2015-04-01 > -- Description : < Performs search for the users > -- =============================================ALTER PR... | C # XML documentation of Linq to SQL |
C# | I 'm making a pong game . I 've been using a simple 44 x 44 .png of a red square as my ball while I 've been debugging . The game works fine with this square.When I try to replace the texture with anything other than a square , I do n't see the ball drawn on screen , and I ca n't figure out why . I 'm making my images ... | public class Ball : IGameEntity { # region Fields private Random rand ; // Random var private Texture2D texture ; // Texture for the ball private double direction ; // Directon the ball is traveling in private bool isVisible ; private bool hasHitLeftBat ; // Checked to see if the ball and bat have just collided private... | Can not draw image over than square in XNA |
C# | I have the following ugly code : Is there a way to chain check for null values in C # , so that I do n't have to check each individual level ? | if ( msg == null || msg.Content == null || msg.Content.AccountMarketMessage == null || msg.Content.AccountMarketMessage.Account == null || msg.Content.AccountMarketMessage.Account.sObject == null ) return ; | Is there such a thing as a chained NULL check ? |
C# | Why does url decode not get an error when it decodes % 22 . This is a double quote . When a programmer enters a double quote in a string syntactically they must use two double quotes `` '' to represent a double quote.For ExampleOutputIt '' s nice to meet youBut when url decodes a double quotes why does it not break . A... | string myString = `` It\ '' s nice to meet you '' ; console.write ( myString ) ; string myString = `` It % 22s nice to meet you '' ; myString = HttpUtility.UrlDecode ( myString ) ; console.Write ( myString ) ; | What is the logic behind url decoder when using double quotes ? |
C# | I 'm working in a code base which has a lot of first class collections.In order to ease using these collections with LINQ , there is an extension method per collection that looks like : With the accompanying constructors : This winds up being a bunch of boilerplate so I attempted to write a generic IEnumerable < U > .T... | public static class CustomCollectionExtensions { public static CustomCollection ToCustomCollection ( this IEnumerable < CustomItem > enumerable ) { return new CustomCollection ( enumerable ) ; } } public class CustomCollection : List < CustomItem > { public CustomCollection ( IEnumerable < CustomItem > enumerable ) : b... | Generic extension method to convert from one collection to another |
C# | I want to chunk a credit card number ( in my case I always have 16 digits ) into 4 chunks of 4 digits.I 've succeeded doing it via positive look ahead : But I do n't understand why the result is with two padded empty cells : I already know that I can use `` Remove Empty Entries '' flag , But I 'm not after that.However... | var s= '' 4581458245834584 '' ; var t=Regex.Split ( s , '' ( ? = ( ? : ... . ) * $ ) '' ) ; Console.WriteLine ( t ) ; | Split credit card number into 4 chunks using Regex lookahead ? |
C# | I usually use many EF Core async methods in my web application like this : As we know , initial number of threads in ThreadPool by default is limited to number of CPU logical cores . Also user requests are handled by threads in ThreadPool . Should I worry about handling user requests or performance issues due to many a... | await db.Parents.FirstOrDefaultAsync ( p = > p.Id == id ) ; | Do Entity Framework async methods consume ThreadPool threads ? |
C# | The following code produces a syntax error : However , the following alternatives both work : Why is this so ? ( foo.a ) is an Action ; why ca n't I call it ? | class Foo { public Action a = ( ) = > { } ; } void doSomething ( ) { var foo = new Foo ( ) ; ( foo.a ) ( ) ; // error CS1525 : Invalid expression term ' ) ' } foo.a ( ) ; // worksAction a = foo.a ; a ( ) ; // works | Why is it invalid syntax to call an Action member in this way ? |
C# | I have to do a search to return a value , I have to do is the sum of multiplying two fields.I have the following code : It is giving the following error : the variable 'acct ' type 'tem ' is referenced in scope `` , but it is not setHow can i return this value ? | internal double TotalRes ( long Id ) { double total = 0 ; Reserve rAlias = null ; var query = Session.QueryOver < Item > ( ) ; query = query.JoinAlias ( e = > e.Reserve , ( ) = > rAlias ) ; query = query.Where ( ( ) = > rAlias.Id == Id ) ; query = query.Select ( Projections.Sum < Item > ( acct = > acct.Ammount * acct.W... | Make a multiplication in a SQL |
C# | I 'm trying to write the following method using generics . ( My actual method is more complex than this . ) My goal is to return something like null if the item is not in the dictionary.The problem is that I do n't know what type T is . If T was an integer , for example , then I should return the type T ? . However , i... | public T ParseDictionaryItem < T > ( string s , Dictionary < string , T > dictionary ) { T result ; if ( dictionary.TryGetValue ( s , out result ) ) return result ; // TODO : Return special value such as null to indicate invalid item } | Returning Null Value for Unknown Type |
C# | I have some code that when called calls a webservice , queries a database and fetches a value from local cache . It then combines the return values from these three actions to produce its result . Rather than perform these actions sequentially I want to perform them asynchronously in parallel . Here 's some dummy/examp... | var waitHandles = new List < WaitHandle > ( ) ; var wsResult = 0 ; Func < int > callWebService = CallWebService ; var wsAsyncResult = callWebService.BeginInvoke ( res = > { wsResult = callWebService.EndInvoke ( res ) ; } , null ) ; waitHandles.Add ( wsAsyncResult.AsyncWaitHandle ) ; string dbResult = null ; Func < stri... | c # threading async problem |
C# | I tried to convert the default template for `` Service Fabric Applicatoin '' with `` Actor Service '' from C # to F # . Here is the github repo.I can compile everything but when I deploy it to the local cluster I get System.ArgumentNullException . Does anyoune know what is wrong here ? Here is the stack trace ( it 's i... | bei System.Reflection.Emit.FieldBuilder..ctor ( TypeBuilder typeBuilder , String fieldName , Type type , Type [ ] requiredCustomModifiers , Type [ ] optionalCustomModifiers , FieldAttributes attributes ) bei System.Reflection.Emit.TypeBuilder.DefineFieldNoLock ( String fieldName , Type type , Type [ ] requiredCustomMod... | Service Fabric with F # not working |
C# | I have a class containing a collection of items . For convenience I 've provided GetCurrentItem which is implemented bywhich will throw an exception if there are no items in the list . Should I let the exception be thrown or should I return null ? If this was an API I handed to you , what would you expect ? The excepti... | public Type GetCurrentItem { get { return this.items [ this.items.Count - 1 ] ; } } | Creating property which may throw IndexOutOfRangeException |
C# | I 'm sure I 've seen this in various exception messages in the framework . I checked the following pages from the MSDN library but could not find much guidance for the message contents : Exception ThrowingError Message DesignException.Message PropertyThe only part in the first page that could explain it is this text : ... | System.ArgumentException : An item with the same key has already been added . System.ArgumentException : An item with the same key ( 123 ) has already been added . | Why do built in exception messages tend to not have specific details ? ( e.g . key from a dictionary ) |
C# | Code contracts simply treats Tasks as it would with any other variable , instead of waiting for the result asynchronously . So , the following scenario will not work , and cause a Contracts exception since at the time the method returns , its an incomplete task , and the results would n't be set at that point in time .... | public Task LoadAppModel ( ) { Contract.Ensures ( app.User ! = null ) ; Contract.Ensures ( app.Security ! = null ) ; Contract.Ensures ( app.LocalSettings ! = null ) ; return Task.WhenAll ( store.GetUserAsync ( ) .ContinueWith ( t = > { app.User = t.Result ; } ) , store.GetSecurityAsync ( ) .ContinueWith ( t = > { app.S... | Code Contracts and Tasks |
C# | I have wrote the following code : resharper shows me a warning : Possible duplicate enumeration of IEnumerableWhat does this mean ? Why is this a warning ? | IEnumerable < string > blackListCountriesCodes = pair.Criterion.CountriesExceptions.Select ( countryItem = > countryItem.CountryCode ) ; IEnumerable < string > whiteListCountriesCodes = pair.Criterion.Countries.Select ( countryItem = > countryItem.CountryCode ) ; return ( ! blackListCountriesCodes.Contains ( Consts.ALL... | Possible duplicate enumeration of IEnumerable |
C# | I have a class which has been steadily growing over time . It 's called LayoutManager . It started as a way for me to keep track of which dynamically created controls were on my page . So , for instance , I have this : In this way , during the beginning stages of the Page Lifecycle , controls would be re-created and th... | public CormantRadDockZone ( ) { ID = String.Format ( `` RadDockZone_ { 0 } '' , Guid.NewGuid ( ) .ToString ( ) .Replace ( '- ' , ' a ' ) ) ; MinHeight = Unit.Percentage ( 100 ) ; BorderWidth = 0 ; HighlightedCssClass = `` zoneDropOk '' ; CssClass = `` rightRoundedCorners '' ; LayoutManager.Instance.RegisteredDockZones.... | Trying to shy away from a singleton/god/manager class . Not sure how I am supposed to sustain functionality , though |
C# | Few Days back , I faced a test where I was asked to answer the following question : Though it seems basic , I 've some doubt and my own opinionA publication center publishes books . A writer can write many books and a book has a authorThere were four options and among them , I omitted two options that were n't close . ... | public class Publisher { public int PublisherId { get ; set ; } public string PublisherName { get ; set ; } public string Address { get ; set ; } public List < Author > Authors { get ; set ; } public List < Book > Books { get ; set ; } } public class Author { public int AuthorId { get ; set ; } public string AuthorName... | List Vs Array : One-To-Many and Has-A Relationship |
C# | I 've come across the problem regarding asynchronous tasks in a dictionary in a couple programs now , and I ca n't wrap my head around how to solve it.I have an asynchronous task that looks like this : MessageEventArgs is a class from a 3rd party library that I declare statically at the start of my program : The progra... | MessageEventArgs.Channel.SendMessage ( `` somestring '' ) ; public static MessageEventArgs meargs ; public static Dictionary < string , Task > myDict= new Dictionary < string , Task > ( ) { { `` ! example '' , MessageEventArgs.Channel.SendMessage ( `` HelloWorld '' ) } } MessageReceived += async ( s , e ) = > { meargs ... | Referencing asynchronous tasks in a c # dictionary |
C# | I am working on a `` learning program '' and using the Code Rush refactoring tool with my learning . With the latest update of Code Rush it has been recommending implementing IDisposable to my programs . I know what MSDN says about IDisposable and I have a real basic understanding of what it does but because I do n't k... | class Program : IDisposable { static Service _proxy ; public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) if ( _proxy ! = null ) { _proxy.Dispose ( ) ; _proxy = null ; } } ~Program ( ) { Dispose ( false ) ; } | What is this IDisposable doing for me ? |
C# | I ca n't understand how to solve the problem that the teacher gave me . Given a number N ( 0 < = N < = 100 ) , find its first digit . For example : It seemed easy at first , but ( as the teacher said ) it should be done using ONLY integer data types ( in other words , using + , - , * , / and % operators ) . Is it even ... | input : 100result : 1input : 46result : 4input : 3result : 3 | Find first digit of a number using ONLY integer operations |
C# | I am unsure of whether what I am doing is completely invalid or merely poor practice , but I have a class , let 's call it Bar , which is a field of some parent class , let 's call Foo , and one of Bar 's methods requires that I pass the instance of the parent Foo as an argument . This seems like a terrible and messy i... | public class Foo { public List < Bar1 > bar1List { get ; set ; } public List < Bar2 > bar2List { get ; set ; } } public abstract class Bar { //EDITED TO IMPROVE EXAMPLE public int Value { get ; set ; } public void DoSomething ( Foo parentFoo ) { } } public class Bar1 : Bar { public override void DoSomething ( Foo paren... | How to deal with passing a parent object as an argument ? |
C# | So I see that Assert has dozens of methods that seem to do essentially the same thing . Why ? Is it just to be more explicit ? When should the various methods be used ? Is there an offical best practices document ? | Assert.IsFalse ( a == b ) ; Assert.IsTrue ( a ! = b ) ; Assert.AreNotEqual ( a , b ) ; | Why does the `` Assert '' class have so many seemingly redundant methods ? When should each be used ? |
C# | I am trying to load some BitmapImages from files held on the file system . I have a dictionary of keys and relative filepaths . Unfortunately the Uri constructor seems non deterministic in the way that it will load the images.Here is my code : Unfortunately sometimes the Uris get loaded as relative file Uris and someti... | foreach ( KeyValuePair < string , string > imageLocation in _imageLocations ) { try { BitmapImage img = new BitmapImage ( ) ; img.BeginInit ( ) ; img.UriSource = new Uri ( @ imageLocation.Value , UriKind.Relative ) ; img.EndInit ( ) ; _images.Add ( imageLocation.Key , img ) ; } catch ( Exception ex ) { logger.Error ( `... | c # Uri loading non deterministic ? |
C# | I have the following scenario when grouping a collection : where data variable is of type ObservableCollection < Data > When I check forit throws an IndexOutOfRangeExceptionof course this happens because the string split operation throws an exception.The question is : is there a way to check if the result of the groupi... | var result = data.GroupBy ( x = > x.Name.Split ( new char [ ] { '- ' } ) [ 1 ] .Trim ( ) ) ; if ( result.Count ( ) > 0 ) | C # IEnumerable.Count ( ) throws IndexOutOfRangeException |
C# | What are the differences between this two methods that seems to do the same thing ? Can it be done even with async/await ? | public Task < int > TaskMaxAsync1 ( Task < int > [ ] my_ints ) { return Task.WhenAll ( my_ints ) .ContinueWith ( x = > x.Result.Where ( i = > i % 2 ! = 0 ) .Max ( ) ) ; } public Task < int > TaskMaxAsync2 ( Task < int > [ ] my_ints ) { var numbers = Task.WhenAll ( my_ints ) .Result ; return Task.FromResult ( numbers.Wh... | C # Differences between Result and ContinueWith |
C# | I have a list of strings which holds file paths . I have another list which holds a subset of files – but it has only the file name ; not the path.Now I need to get files from allFilesWithPathList that is not present in excludeList . Currently I am doing the following , using EXCEPT , after creating another list with f... | List < string > allFilesWithPathList = new List < string > ( ) ; allFilesWithPathList.Add ( @ '' G : \Test\A.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\B.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\C.sql '' ) ; return allFilesWithPathList ; List < string > excludeList = new List < string > ( ) ; excl... | Except with LIKE condition in LINQ |
C# | The reason I am asking is because I wrote an extension method to use in Silverlight only to find out that feature magically started working for silver light . Example Why is there a special System dll in the framework for Silverlight that does the comparsion as case insenstive ? I have run into this for tons of methods... | string sentence = `` I am a sentence that has some words '' ; sentence.Contains ( `` N '' ) ; //would return false , silverlight truesentence.Contains ( `` n '' ) ; //would return true , silverlight true | Is there a reason why System dll is different in Silverlight and other C # Libraries |
C# | In VB you can have this : But in C # , you ca n't do this : Because you get an error `` Keyword 'this ' is not available in the current context '' .I found this question/answer which quotes the C # language specification section 7.6.7:7.6.7 This accessA this-access is permitted only in the block of an instance construc... | Class One Private myTwo As Two = New Two ( Me ) End ClassClass Two Sub New ( withOne As One ) End SubEnd Class class One { private Two myTwo = new Two ( this ) ; } class Two { public Two ( One withOne ) { } } | Why does VB not prevent the use of `` Me '' in field initialization like C # does with `` this '' ? |
C# | I have a HashSet < int > and a List < int > ( Hashset has approximately 3 Million items , List has approximately 300k items ) .I currently intersect them usingand I wonder if there is any faster way to do so . Maybe in parallel ? | var intersected = hashset.Intersect ( list ) .ToArray ( ) ; | Fast intersection of HashSet < int > and List < int > |
C# | I have a situation where , for testing , I only want my timer method ( FooMethod ) to run one at a time . In the example below , FooMethod is passed as the delegate to a timer . There are many concrete instances of this class . I thought that by making _locker static , only one instance of FooMethod ( ) would process a... | _timers.Add ( new Timer ( foo.FooMethod , null , 0 , 10000 ) ) ; public class Foo < T > { private static readonly object _locker = new object ( ) ; public void FooMethod ( object stateInfo ) { // Do n't let threads back up ; just get out if ( ! Monitor.TryEnter ( _locker ) ) { return ; } try { // Logic here } finally {... | Monitor.TryEnter with Generic Class |
C# | I have a ten element array of integers . I want to sum the elements by group , so for instance I want to add the value at element 0 with the value at element 1 , then with the value at element 2 , then 3 , and so on through to element 9 , then add the value at element 1 with the value at 2,3 , through to 9 until every ... | int i = 0 ; int p = 1 ; int q = 2 ; int r = 3 ; while ( i < NumArray.Length - 3 ) { while ( p < NumArray.Length - 2 ) { while ( q < NumArray.Length-1 ) { while ( r < NumArray.Length ) { foursRet += NumArray [ i ] + NumArray [ p ] + NumArray [ q ] + NumArray [ r ] ; r++ ; } q++ ; r = q + 1 ; } p++ ; q = p + 1 ; r = q + ... | Adding elements of an array |
C# | I am testing my run ( ) function to make sure it has all the correct things populated by the end of the method . I populate 4 fields from our databases , two strings , and two IEnumerable ( string ) 's . The idea is to print them all out for all the people I am pulling from the database.When I only print the string fie... | int i = 0 ; foreach ( Contact contact in Contact.LoadWithPredicate ( getAll ) ) { -- -- -- -other code to populate fields -- -- -- -- - i ++ ; Console.WriteLine ( i ) ; //Turn the Enumerables into strings for printing string firstEnumAsString = String.Join ( `` , `` , firstEnumerable.ToArray ( ) ) ; string secondEnumAs... | Does Console.Write ever fail ? |
C# | ( All of the below are simplified for brevity ) I have a static reference to a processing object.The Processor contains a function to which I can pass an object Package , which is the info to be processed.The Package comes from a list of lots of packages which should be processed . These packages are unqique ; there ar... | static class Program { static Processor processor = new Processor ( ) ; static Stack < Package > toProcess ; static Object sync = new Object ( ) ; static void RunThreads ( ) { toProcess = GetPackages ( ) ; //start many threads using the Work delegate } static void Work ( ) { while ( true ) { Package p ; lock ( sync ) {... | Will parameter of a static object 's non-static method be shared from multiple threads ? |
C# | I 'm trying to download a composition media file into my hard drive using the following code : But every time I get an exception with this message : `` The remote server returned an error : ( 302 ) FOUND . `` Note that this method is called after Twilio calls my StatusCallback method which I 've set when creating a new... | try { var uri = `` https : //video.twilio.com/v1/Compositions/ '' + sid + `` /Media ? Ttl=6000 '' ; var request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; request.Headers.Add ( `` Authorization '' , `` Basic `` + Convert.ToBase64String ( Encoding.ASCII.GetBytes ( _apiKeySid + `` : '' + _apiKeySecret ) ) ) ; reque... | C # Twilio retrieve composition media |
C# | I need to analyze some extension method . For example Enumerable.ToList.Code sample to analyze : Diagnostic : However symbolInfo.Symbol is null and there are no any candidates . If I change the code sample like that : then symbolInfo has a candidate but still does n't have Symbol . How to get a symbol info of extension... | var test = @ '' using System.Linq ; namespace Test { public class TestType { void TestMethod ( ) { var empty = new [ ] { 0 } ; var test = empty.ToList ( ) ; } } } '' ; public override void Initialize ( AnalysisContext context ) { context.RegisterSyntaxNodeAction ( AnalyzeSymbol , SyntaxKind.InvocationExpression ) ; } p... | SymbolInfo of extension method |
C# | Currently in my game i want trying to move my object towards both x axis and y axis.As I also wanted to put it into center , I have put a camera.Here is my Camera code-and in Game1.cs file as usual in begin statement i am putting this-Here ba is the object of ball , its just have moving x and y functionalities.In a sep... | public class Camera { public Matrix transform ; public Viewport view ; public Vector2 origin ; Vector2 baseScreenSize = new Vector2 ( 1136 , 720 ) ; float horScaling ; float verScaling ; Vector3 screenScalingFactor ; public Camera ( Viewport newView ) { view = newView ; horScaling = view.Width / baseScreenSize.X ; verS... | Need help on monogame screen resolution and intersection |
C# | Hi I see following code : Why using Action and then invoke action here ? Why not just using txtMessage.Text = message to replace the code in function body ? UpdateA fuller version of the code , presented in a comment , reproduced below with syntax highlighting , indentation etc . | void UpdateMessage ( string message ) { Action action = ( ) = > txtMessage.Text = message ; this.Invoke ( action ) ; } public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; new Thread ( Work ) .Start ( ) ; } void Work ( ) { Thread.Sleep ( 5000 ) ; UpdateMessage ( `` My Garden '' ) ; } void Up... | Why using Action in this code ? |
C# | I can not understand why the above code ( modified from the actual codes ) always gives me weird result : '' ZXCV ) '' instead of `` Tom ( ZXCV ) '' .Does anybody knows the reason behind and can provide a reference if possible ? | StringBuilder htmlResp=new StringBuilder ( ) ; int ? cuID= 1 ; string cuName= '' Tom '' ; string cuEmpID= '' ZXCV '' ; htmlResp .Append ( `` < option value=\ '' '' + cuID.Value + `` \ '' > '' + cuName+ '' ( `` +cuEmpID== '' '' ? `` - '' : cuEmpID+ '' ) '' + `` < /option > '' ) ; html.Resp.ToString ( ) ; | Why the following Conditional Operator works strangely in StringBuilder containing Nullable type ? in C # ? |
C# | Why does the compiler reject this code with the following error ? ( I am using VS 2017 with C # 7.3 enabled . ) CS0019 Operator '== ' can not be applied to operands of type 'T ' and 'T'The version without generics is of course perfectly valid . | public class GenericTest < T > where T : Enum { public bool Compare ( T a , T b ) { return a == b ; } } public enum A { ONE , TWO , THREE } ; public class Test { public bool Compare ( A a , A b ) { return a == b ; } } | C # Enums and Generics |
C# | Lets forgot about why I need this.Can we create a class with name `` class '' .Below code resulted in compilation error as class is a reserve keyword.so is there any hack or a way to fool C # compiler ? : ) This Question was asked by interviewer in my last interview and he told me it is possible . | public class class { } | Can we create class with name `` class '' ? |
C# | I have a multi layered project with a web API project and a library project . Both projects rely on AutoMapper ( and AutoMapper extensions for Microsoft.Extensions.DependencyInjection ) . Based on thishttps : //docs.automapper.org/en/latest/Dependency-injection.html # asp-net-corein the Startup file I 'm setting up Aut... | Assembly apiAssembly = Assembly.GetExecutingAssembly ( ) ; Assembly myLibraryAssembly = Assembly.Load ( `` MyLibrary '' ) ; services.AddAutoMapper ( apiAssembly , myLibraryAssembly ) ; public static class DependencyInjection { public static IServiceCollection AddMyLibrary ( this IServiceCollection services ) { Assembly... | calling AddAutoMapper once per assembly instead of passing in multiple assemblies ? |
C# | I have the following if condition param.days is a string.This works fine , but if I saythen it does not evaluate correctly at runtime . Both statements are not the same in C # .It does say that the value is null but then C # tries to cast it to a bool which is non-nullable.Why did the C # designers choose to do it this... | if ( param.days ! = null ) If ( param.days ) | Why is n't this allowed in C # ? |
C# | GoalI have a couple of interfaces and some dlls that provide implementations for these interfaces . I want to load the implementation into a new AppDomain ( so I can unload the dll later ) and instatiate the implementation in the new AppDomain and then use a clientside ( here the default AppDomain ) proxy to wrap the a... | public interface IData { int Foo { get ; set ; } } public interface ILogic { void Update ( IData data ) ; } public class DataImpl : MarshalByRefObject , IData { public int Foo { get ; set ; } } public class LogicImpl : MarshalByRefObject , ILogic { public void Update ( IData data ) { data.Foo++ ; } } class AssemblyLoad... | Wrapping __TransparentProxy of RemotingProxy in another Proxy throws RemotingException |
C# | UPDATE 10:29 MST on 11/7Oddly enough if I move the attribute out of the ComponentModel folder back into the root of the Common project the code works fine . I ca n't imagine what 's possibly referencing the old namespace after all of the references were refactored for the InflowHealth.Common.ComponentModel namespace.It... | public static void MapInheritedAttributeRoutes ( this HttpConfiguration config ) { config.MapHttpAttributeRoutes ( new InheritanceDirectRouteProvider ( ) ) ; } public class InheritanceDirectRouteProvider : DefaultDirectRouteProvider { protected override IReadOnlyList < IDirectRouteFactory > GetActionRouteFactories ( Ht... | TypeLoadException on Attribute in shared assembly |
C# | I 've always used role authorization in my .net application . However , I 'm building a demo app and want to give claims a try . I 've always decorated my controller like this where either an admin or User with full access can be authorized.However , I ca n't accomplish the same with claims . In my startup , I have the... | [ [ Authorize ( Roles = `` IsApiUserFullAccess '' , `` IsAdmin '' ) ] ] options.AddPolicy ( `` IsApiUserFullAccess '' , policy = > policy.RequireClaim ( `` apiuser.fullaccess '' , `` true '' ) ) ; options.AddPolicy ( `` IsAdmin '' , policy = > policy.RequireClaim ( `` administrator '' , `` true '' ) ) ; | Is it possible to have a claims authorization with an OR condition like roles ? |
C# | Firstly I need to get all the data from ODBC ( this is working already ) . Then comes the most complicated part that I am not sure yet how it can be done . There are two tables of data in ODBC . I am merging them with my current code and filtering them with certain parameters.Table 1 in database : Table 2 in database :... | NRO NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR COMPANYN COUNTRY ID ACTIVE123 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1133 Opel Meriva FTG J5 K4 O3 P4 O2 JO 3 1153 MB E200 C25 JN KI OP PY OR JD 5 1183 BMW E64 SE0 JR KE OT PG OL J8 9 1103 Audi S6 700 JP KU OU PN OH J6 11 1 NRO NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR CO... | Build one datatable out of two with certain conditions |
C# | QUESTION : How do I apply my personal DocumentationProvider to source tree symbols ? Which is the type of symbol i get when i use the SymbolFinder.FindSymbolAtPosition ( ) Specifically I want to override the GetDocumentationForSymbol ( ) function . I have it overridden for my autocomplete symbols but not the symbols i ... | compilation = CSharpCompilation.Create ( `` MyIntellisense '' , new [ ] { CSharpSyntaxTree.ParseText ( dotNetCode ) } , assemblies .Select ( i = > MetadataReference .CreateFromFile ( i.Location , MetadataReferenceProperties.Assembly , new DotNetDocumentationProvider ( new CSharpCompilationOptions ( OutputKind.Dynamical... | Using roslyn for hover over data for source tree symbols |
C# | Possible Duplicate : Why is Func < T > ambiguous with Func < IEnumerable < T > > ? I noticed a very weird overload resolution issue with generics ... Consider the following methods : ( C # 4 , tested in LINQPad ) If I try to call Foo with a lambda expression as the selector , everything works fine : But if I replace x ... | static void Foo < TSource > ( TSource element , Func < TSource , int > selector ) { `` int '' .Dump ( ) ; } static void Foo < TSource > ( TSource element , Func < TSource , double > selector ) { `` double '' .Dump ( ) ; } static T Identity < T > ( T value ) { return value ; } Foo ( 42 , x = > x ) ; // prints `` int '' ... | Generics , overload resolution and delegates ( sorry , ca n't find a better title ) |
C# | I 've look in many places including google and SO but I did n't find any relevant answer.I 've made a few changes in my app recently , including updating ZedGraph dll ( from 5.1.4.26270 to 5.1.6.405 ) and since , VS wo n't open my controls throwing this error : Could not load file or assembly 'ZedGraph , Version=5.1.4.... | this.lineGraphControl1 = new Sakura.UI.Graphing.LineGraphControl ( ) ; < Reference Include= '' ZedGraph , Version=5.1.4.26270 , Culture=neutral , PublicKeyToken=02a83cbd123fcd60 , processorArchitecture=MSIL '' > < SpecificVersion > False < /SpecificVersion > < HintPath > ..\..\Lib\ZedGraph.dll < /HintPath > < /Referenc... | VS wo n't open control since dll update |
C# | The following code produces a CA2000 ( `` Dispose objects before losing scope '' ) violation for the first line of Main , but not the second . I would really like the CA2000 violation for the second line , because this is a ( obviously simplified ) pattern often found in a large code base I work on . Does anyone know w... | public static void Main ( ) { new Disposable ( ) ; MakeDisposable ( ) ; } private static Disposable MakeDisposable ( ) { return new Disposable ( ) ; } private sealed class Disposable : IDisposable { public void Dispose ( ) { } } | Why does FxCop not report CA2000 for this trivial case of not-disposed class instance ? |
C# | For money I am using a custom value type which holds only one decimal field . Simplified code is as follows.While using this struct in my project sometimes an ambiguity arises . And also sometimes I am setting an object with a constant number which is supposed to be a Money . For now I am initializing the object like ,... | public struct Money { private decimal _value ; private Money ( decimal money ) { _value = Math.Round ( money , 2 , MidpointRounding.AwayFromZero ) ; } public static implicit operator Money ( decimal money ) { return new Money ( money ) ; } public static explicit operator decimal ( Money money ) { return money._value ; ... | Can I assign a suffix to my custom value type ? |
C# | So I 've got these classes that expose a collection of child objects.I do n't want other classes adding or removing objects from collections because I need to wire into events in the child objects , so as they get added or removed I want to be able to do additional processing . But I really love the ease of manipulatin... | public class foo : INotifyPropertyChanged { protected List < ChildFoo > _Children = new List < ChildFoo > ( ) ; public foo ( ) { } public void AddChild ( ChildFoo newChild ) { DoAttachLogic ( newChild ) ; _Children.Add ( newChild ) ; NotifyPropertyChange ( `` Children '' ) ; } public void RemoveChild ( ChildFoo oldChil... | Is there a good pattern for exposing a generic collection as readonly ? |
C# | I have a c # class which looks likeFrom a browser , I submitted a JSON object as followsWhere the value 1 assigned to the ParentNode property representes a database identifier . So , in order to bind properly to my model , i need to write a custom JSON converterBecause i get a `` Current JsonReader item is not an objec... | public class Node { public int Id { get ; set ; } /** Properties omitted for sake of brevity **/ public Node ParentNode { get ; set ; } } { `` Id '' :1 , `` ParentNode '' :1 } public class NodeJsonConverter : JsonConverter { public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , ... | How to bind a given property when deserializing a JSON object in c # Web Api ? |
C# | I would like to run this function under mono ( my current version is 4.0.2 ) But it fails with the error : What is the Mono equivalent of ClientConnectionId ? Or how can I fix it ? | public Object GetConnectionProperty ( SqlConnection _conn , string prop ) { if ( _conn.State == ConnectionState.Closed & prop == `` ServerVersion '' ) return string.Empty ; if ( prop == `` ClientConnectionId '' ) { Guid guid = _conn.ClientConnectionId ; return guid.ToString ( ) ; } return _conn.GetType ( ) .GetProperty... | Mono equivalent of ClientConnectionId |
C# | I have a scenario where a class loads objects of one type , due do abstractions I can not use a generic class ( generics tend to spread like cancer : ) but I often want to work with a generic version of the objects once retrieved , which resulted in code like this ( simplified ) : Where LoadItems returns a List < objec... | List < SomeClass > items = Storage.LoadItems ( filename ) .OfType < SomeClass > ( ) .ToList ( ) ; public void LoadItems ( string filename , IList list ) ; List < SomeClass > items = new List < SomeClass > ( ) ; LoadItems ( filename , items ) ; public IList LoadItems ( string filename , IList list=null ) ; | Backdooring Generic Lists through IList |
C# | i am implementing Floyd–Warshall algorithm with c++ , c # and java . in each language i use sequential and parallel implementation after testing the result was : ( Elapsed time is only for main Function and Reading Files , Inti of Variable and ... are not measured . ) download sources here SourceCodesc++IDE : NetbeansC... | # define n 1000 /* Then number of nodes */double dist [ n ] [ n ] ; void floyd_warshall ( int NumOfThreads ) { int i , j , k ; omp_set_num_threads ( NumOfThreads ) ; for ( k = 0 ; k < n ; ++k ) # pragma omp parallel for private ( i , j ) for ( i = 0 ; i < n ; ++i ) for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i ] [ k ] * ... | Comparing c # , c++ and java performance ( Strange behavior of c # ) |
C# | can I get a hand converting the following into a LINQ statement.Currently I have it down to this : The problem with the LINQ above is that it returns entries that have titles changed . Within the database I keep history of all records ( hence the need for the first on the createdDate order descending . When I change a ... | SELECT reports . * FROM [ dbo ] . [ ReportLists ] rlINNER JOIN [ dbo ] . [ ReportItems ] ri ON rl.Id = ri.ReportListIdINNER JOIN [ dbo ] . [ Reports ] reports ON ri.Id = reports.ReportItemIdWHERE reports.createdDateIN ( SELECT MAX ( report_max_dates.createdDate ) FROM [ dbo ] . [ Reports ] report_max_dates GROUP BY rep... | Convert an SQL statement into LINQ-To-SQL |
C# | I would like to call one method 3 times Using LINQ , the method returns an object , with that object I want to add it into a List , How do i do it ? | List < News > lstNews = new List < News > ( ) ; lstNews.Add ( CollectNews ) [ x 3 times ] < -- Using Linq private static News CollectNews ( ) { ... } | Call method x times using linq |
C# | I am getting the following error in an editor template of mine , ApplicantAddressMode : error CS0019 : Operator ' ! = ' can not be applied to operands of type 'Comair.RI.ViewModels.ApplicantAddressType ' and 'Comair.RI.Models.ApplicantTypesOfAddress ' '' } The type Comair.RI.ViewModels.ApplicantAddressType is nowhere t... | @ using Comair.RI.Models @ model Comair.RI.ViewModels.ApplicantAddressModel @ Html.ValidationSummary ( true ) < fieldset > < legend > @ Model.AddressTypeDescription < /legend > < ul class= '' form-column '' > @ if ( Model.AddressType ! = ApplicantTypesOfAddress.Residential ) { [ ScaffoldColumn ( false ) ] public Applic... | Why am I getting a type mismatch error with a type I can not see anywhere in my solution ? |
C# | I understand why GUI controls have thread affinity.But why do n't the controls use the invoke internally in their methods and properties ? Now you have to do stuff like this just to update TextBox value : While using just textBox.Text = `` newValue '' ; would be enough to represent the same logic . All that would have ... | this.Invoke ( new MethodInvoker ( delegate ( ) { textBox.Text = `` newValue '' ; } public string Text { set { if ( ! this.InvokeRequired ) // do the change logic else throw new BadThreadException ( ) ; } } public string Text { set { if ( ! this.InvokeRequired ) // do the change logic else this.Invoke ( new MethodInvoke... | Why do n't WinForms/WPF controls use Invoke internally ? |
C# | Have a collection of objects . Schematically : Need : Is it possible to LINQ such ? Note : Ordering is important . So Bs = [ 5 ] ca n't be merged with Bs = [ 1 , 2 ] | [ { A = 1 , B = 1 } { A = 1 , B = 2 } { A = 2 , B = 3 } { A = 2 , B = 4 } { A = 1 , B = 5 } { A = 3 , B = 6 } ] [ { A = 1 , Bs = [ 1 , 2 ] } { A = 2 , Bs = [ 3 , 4 ] } { A = 1 , Bs = [ 5 ] } { A = 3 , Bs = [ 6 ] } ] | Transform a collection |
C# | I have an object that looks something like this ( obviously simplified ) What I would like is for ETag to be a hash of the json serialization of the object omitting the ETag property ( to prevent a recursive loop ) . However , I can not just use a [ JsonIgnore ] attribute since at other times I want to be able to json ... | public class Person { public string Name { get ; set ; } public int Age { get ; set ; } public string ETag { get { return ... } } } public string ETag { get { return Hash ( JsonConvert.Serialize ( this , p = > p.Ignore ( x= > x.ETag ) ) ) ; } } | How to serialize all but a specific property in one specific serialization |
C# | How can I wait for n number of pulses ? I want the above thread to wait until being notified n times ( by n different threads or n times by the same thread ) .I believe there is a type of counter to do this , but I ca n't find it . | … // do somethingwaiter.WaitForNotifications ( ) ; | Let a thread wait for n number of pulses |
C# | I have written some test code for comparing the performance of using direct property access or reflection or reflection by using delegates . But the results that I get are baffling , since it is showing that reflection is not much slower ( ~4 % ) than direct property access , which I do not believe to be true . Could s... | private static Random random = new Random ( ( int ) DateTime.Now.Ticks ) ; Private Dictionary < string , Delegate > delegateList = new Dictionary < string , Delegate > ( ) ; private List < ReflectClass1 > dataList = new List < ReflectClass1 > ( ) ; private void TestMethod2 < T > ( ) { foreach ( var propertyInfo in type... | Reflection test does not show expected numbers |
C# | I 'll try to make this as clear as possible . A Plugin architecture using reflection and 2 Attributes and an abstract class : PluginEntryAttribute ( Targets.Assembly , typeof ( MyPlugin ) ) PluginImplAttribute ( Targets.Class , ... ) abstract class Plugin Commands are routed to a plugin via an interface and a delegate ... | public static TResult Execute < TTarget , TResult > ( this Command < TTarget > target , Func < TTarget , TResult > func ) { return CommandRouter.Default.Execute ( func ) ; } public class Repositories { public static Command < IDispatchingRepository > Dispatching = ( o ) = > { return ( IDispatchingRepository ) o ; } ; p... | How to build a dynamic command object ? |
C# | I need to parse DateTime in `` Myy '' format , so : the first number is a month without leading zero ( 1 to 12 ) , andthe second number is a year with two digits.Examples : When using DateTime.ParseExact with `` Myy '' as a format , DateTime throws an exception when month is without leading zero.This code throws an exc... | 115 - > January 20151016 - > October 2016 var date = DateTime.ParseExact ( `` 115 '' , `` Myy '' , CultureInfo.InvariantCulture ) ; // throws FormatException var date = DateTime.ParseExact ( `` 1016 '' , `` Myy '' , CultureInfo.InvariantCulture ) ; // works fine | Parsing DateTime in a `` Myy '' format |
C# | This is more of an academic question about performance than a realistic 'what should I use ' but I 'm curious as I do n't dabble much in IL at all to see what 's constructed and I do n't have a large dataset on hand to profile against.So which is faster : or : Keep in mind that I do n't really want to know the performa... | List < myObject > objs = SomeHowGetList ( ) ; List < string > strings = new List < string > ( ) ; foreach ( MyObject o in objs ) { if ( o.Field == `` something '' ) strings.Add ( o.Field ) ; } List < myObject > objs = SomeHowGetList ( ) ; List < string > strings = new List < string > ( ) ; string s ; foreach ( MyObject... | Which is faster in a loop : calling a property twice , or storing the property once ? |
C# | We build software that audits fees charged by banks to merchants that accept credit and debit cards . Our customers want us to tell them if the card processor is overcharging them . Per-transaction credit card fees are calculated like this : A `` fee scheme '' is the pair of ( fixed , variable ) used by a group of cred... | fee = fixed + variable*transaction_price card_id transaction_price fee fixed variable=======================================================================12345 200 22 ? ? 67890 300 21 ? ? 56789 150 8 ? ? 34567 150 8 ? ? 34567 150 `` rounding cent '' - > 9 ? ? 34567 150 8 ? ? fee_scheme_id fixed variable==============... | given 10 functions y=a+bx and 1000 's of ( x , y ) data points rounded to ints , how to derive 10 best ( a , b ) tuples ? |
C# | I migrated to a Table Azure Provider for managing Microsoft bot framework state.In my telemetry , I see dependencies call being made to my new Table Azure Storage however I still see a lot of calls being made to state.botframework.com and some have the usual random slow response time . This does not seem normal as I wo... | protected override void Load ( ContainerBuilder builder ) { base.Load ( builder ) ; //Register custom datastore builder .RegisterKeyedType < TableBotDataStore , IBotDataStore < BotData > > ( ) .Keyed < IBotDataStore < BotData > > ( AzureModule.Key_DataStore ) .WithParameter ( ( pi , c ) = > pi.Name == `` connectionStri... | Migrated bot state provider but calls to state.botframework.com are still being made |
C# | I have some kind of a job scheduling implemented which calls a function ProcessJob . Now inside this method I need to generate url to one of my pages i.e DoanloadPage.aspx ? some_params . That url is sent to user via email and when user clicks that link , it will take to the page . The problem here is that I am not gen... | HostingEnvironment.MapPath ( `` test.aspx '' ) ; VirtualPathUtility.ToAbsolute ( `` 123.aspx '' ) ; HttpContext.Current.Request.Url.Authority ; | Making relative urls in asp.net webform custom classes without Request |
C# | In this code , is it safe to not await the CopyToAsync or the stream could be disposed before the actual copy is done ? | public Task SaveAsync ( Stream source , string filepath ) { using ( var file = File.OpenWrite ( filepath ) ) { return source.CopyToAsync ( file ) ; } } | Is safe to not await inside a using block ? |
C# | I am building an expression of type Expression < Func < Project , bool > > which returns the correct IQueryable < Project > from the database . IQueryable < Project > has a nested collection of SubProjects that I would like to filter as well . It looks something like thisCan this be done with one call to the database ?... | Expression < Func < Project , bool > > projectFilter = FilterEnabled ( ) ; projectFilter = projectFilter.And ( GetProjectsByOrganization ( ) ) ; var projectData = GetProjectsAsQueryable ( projectFilter ) ; //returns correct projects Expression < Func < Project , bool > > projectFilter = FilterEnabled ( ) ; projectFilte... | How can I filter nested items of IQueryable < T > ? |
C# | Do I have to do this to ensure the MemoryStream is disposed of properly ? or is it OK to inline the MemoryStream so that it simply goes out of scope ? Like this ? | using ( MemoryStream stream = new MemoryStream ( bytes ) ) using ( XmlReader reader = XmlReader.Create ( stream ) ) { return new XmlDocument ( ) .Load ( reader ) ; } using ( XmlReader reader = XmlReader.Create ( new MemoryStream ( bytes ) ) ) { return new XmlDocument ( ) .Load ( reader ) ; } | Can I `` inline '' a variable if it 's IDisposable ? |
C# | I was stepping through .Net Framework source code to find a tricky bug ( HttpApplication.cs ) , and I noticed lines like these in the code ( these are copy/pastes , I did n't edit anything ) : andI 'm wondering if this is obfuscated code , or is this some sort of c # convention I 've never seen before ? VS 2012 seems t... | _ [ ... . ] = true ; _ [ ... . ] = false ; | Weird variable name ( _ [ ... . ] ) in .Net Source Code ( HttpApplication.cs ) |
C# | While attempting to create a .NET Core class library for PowerShell I 'm seeing some strange differences between .NET Standard and .NET Core.Following this guidance , I 've created a simple .NET Standard 2.0 class library and have been able to successfully load it in PowerShell 5.1 and PowerShell 6.0.1 using Add-Type -... | namespace Animal { public class Dog { public string Bark ( ) { return `` Woof ! `` ; } } } namespace AnimalCore { public class Dog { public string Bark ( ) { return `` Woof ! `` ; } } } | Ca n't call/load .NET Core assembly but .NET Standard works fine using Add-Type in PowerShell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.