lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have an import operation I 'd like to execute on another thread , desiring the UI to respond right away . So , I started down the path and created an action like this : The ImportManager now serves two purposes : Handle the import.Notify all clients of the status of the import via SignalR.The StartImport method looks... | [ HttpPost ] public async Task < RedirectToRouteResult > ImportAsync ( HttpPostedFileBase file ) { var importsRoot = Server.MapPath ( `` ~/App_Data/Imports '' ) ; var path = Path.ChangeExtension ( Path.Combine ( importsRoot , Guid.NewGuid ( ) .ToString ( ) ) , `` txt '' ) ; if ( ! Directory.Exists ( importsRoot ) ) { D... | Task.Run is n't running asynchronously like I had thought it would ? |
C# | This error is so weird I Just ca n't really figure out what is really wrong ! In UserController I haveMy view is of type @ model IEnumerable < UserViewModel > on the top.This is what happens : Where and what exactly IS null ! ? I create the users from a fake repository with moq . I also wrote unit tests , which pass , ... | public virtual ActionResult Index ( ) { var usersmdl = from u in RepositoryFactory.GetUserRepo ( ) .GetAll ( ) select new UserViewModel { ID = u.ID , UserName = u.Username , UserGroupName = u.UserGroupMain.GroupName , BranchName = u.Branch.BranchName , Password = u.Password , Ace = u.ACE , CIF = u.CIF , PF = u.PF } ; i... | odd nullreference error at foreach when rendering view |
C# | I created an extension method to encapsule some where logic like this ( this is a very simplified version ) : So I can use it like this : Which works nicely , this is translated to SQL and executed by Entity Framework . Now , I have another place I need cargos which are not ready to carry , which means I need exactly t... | public static IQueryable < Cargo > ReadyToCarry ( this IQueryable < Cargo > q ) { VehicleType [ ] dontNeedCouple = new VehicleType [ ] { VehicleType.Sprinter , VehicleType.Van , VehicleType.Truck } ; return q.Where ( c = > c.DriverId > 0 & & c.VehicleId > 0 ) .Where ( c = > c.CoupleId > 0 || dontNeedCouple.Contains ( c... | How to negate a Where clause of an IQueryable |
C# | I 'm creating a model for an existing database . How do I use nvarchar ( max ) as an attribute to my property ? Do I use an extension to my attribute ? Or is it entirely different . The SQL Server database is using a datatype of nvarchar ( max ) . | [ MaxLength + ? ? ? ] public string Bucket { get ; set ; } | Using NVarChar in asp.net core |
C# | Need to validate the Azure Virtual machine username and password . Now used the following code to validate the Virtual machine username and password.But can not able to validate the Virtual machine credentials while Virtual machines are in shutdown state . Is there any way to validate Virtual machine credentials even w... | $ SecureVmPassword = ConvertTo-SecureString -string $ VmPassword -AsPlainText -Force $ VmCredential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $ Fqdn '' \ '' $ VmUsername , $ SecureVmPasswordInvoke-Command -ConnectionUri $ RemoteConnectionUri.ToString ( ) -Credential $ VmCredential -... | How to validate Azure Virtual machine username and password ? |
C# | I am trying out Resharper and i notice that it is recommending to set instance level fields to readonly . For example : What is the benefit of marking fields like this readonly ? | private readonly IConnection _connection ; public RetrieveCommand ( IConnection connection ) { _connection = connection ; } | Resharper changing fields to readonly |
C# | Here is a small demo of a SQL database , where one can add , update delete members from a SQL server . There are two tables in a single SQL Server DB , one is “ members ” second is “ overview ” . In members there is distinct ID column and members personal info like name , address telephone etc . In overview there are o... | using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Data.SqlClient ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace SQLDatabase { public partial class SQLDBDisplay : Form { SqlConnection con = new SqlConn... | How to achieve a search for a certain year & amount using C # |
C# | I have a case there I need to execute set of validation rules for different companies . There will be multiple validation rules against one Company.So I have following table StructureCompany ValidationRule CompanyValidationRuleMapping I have separate stored procedures for every validation rule.So from my c # code , I w... | ID CompanyName 1 ABC 2 DEF RuleID Name 1 Rule1 2 Rule2 MappingID CompanyId RuleID1 1 12 1 23 2 2 | Execute Set of ValidationRule-C # Class Design - Better Approach |
C# | When I run this bit of code , Equation ( 10 , 20 ) is output to the console : I 'd like to support Equation instances being used in the test of an if so I allowed for implicit conversion to Boolean : However , the trouble is , now when I use WriteLine on an Equation , it get 's converted to a Boolean instead of printin... | public class Equation { public int a ; public int b ; public override string ToString ( ) { return `` Equation ( `` + a + `` , `` + b + `` ) '' ; } } class Program { static void Main ( string [ ] args ) { Console.WriteLine ( new Equation ( ) { a = 10 , b = 20 } ) ; Console.ReadLine ( ) ; } } public class Equation { pub... | Support conversion to Boolean but still have WriteLine display using ToString |
C# | Say that I have a list of valid scheduling days . Something like : 23 , 27 , 29I want to modify a given date to it 's next valid day-month based on the above list.If your given date was `` 23/11/2013 '' the next valid date would be `` 27/11/2013 '' But If your given date was `` 30/11/2013 '' it has to return `` 23/12/2... | SELECT TOP 1 @ DATE = ISNULL ( DateAdd ( yy , YEAR ( @ DATE ) -1900 , DateAdd ( m , ( MONTH ( @ DATE ) +CASE WHEN DATEPART ( day , @ DATE ) > [ DAY ] THEN 1 ELSE 0 END ) - 1 , [ DAY ] - 1 ) ) , @ DATE ) FROM @ DAYS WHERE DateAdd ( yy , YEAR ( @ DATE ) -1900 , DateAdd ( m , ( MONTH ( @ DATE ) +CASE WHEN DATEPART ( day ,... | DateTime shift to next predefined date |
C# | I have a simple method to compare an array of FileInfo objects against a list of filenames to check what files have been already been processed . The unprocessed list is then returned.The loop of this method iterates for about 250,000 FileInfo objects . This is taking an obscene amount of time to compete.The inefficien... | public static List < FileInfo > GetUnprocessedFiles ( FileInfo [ ] allFiles , List < string > processedFiles ) { List < FileInfo > unprocessedFiles = new List < FileInfo > ( ) ; foreach ( FileInfo fileInfo in allFiles ) { if ( ! processedFiles.Contains ( fileInfo.Name ) ) { unprocessedFiles.Add ( fileInfo ) ; } } retur... | I have a non-performant method , how can I improve its efficiency ? |
C# | Possible Duplicate : Why does Enumerable.All return true for an empty sequence ? Code : How it is possible ? it should not return false ? after : is an empty string . | var line = `` name : '' ; Console.Write ( line.Split ( new char [ ] { ' : ' } ) [ 1 ] .All ( char.IsDigit ) ) ; | why this condition returns true ? |
C# | If I create a binary add expression ( addExpression ) of two int literals like this : . . and then a binary multiply expression , where left is addExpression and right is an int literal Calling multExpression.ToString ( ) outputs 10+100*5 . I would expect it to output ( 10+100 ) *5.Is this correct behavior ? | BinaryExpressionSyntax addExpression = SyntaxFactory.BinaryExpression ( SyntaxKind.AddExpression , SyntaxFactory.LiteralExpression ( SyntaxKind.NumericLiteralExpression , SyntaxFactory.Literal ( 10 ) ) , SyntaxFactory.LiteralExpression ( SyntaxKind.NumericLiteralExpression , SyntaxFactory.Literal ( 100 ) ) ) ; BinaryEx... | Roslyn - Calling ToString on SyntaxNode not preserving precedence |
C# | I have written a regex to parse a BibTex entry , but I think I used something that is not allowed in .net as I am getting a Unrecognized grouping construct exception.Can anyone spot my mistake ? Can be seen at https : //regex101.com/r/uM0mV1/1 | ( ? < entry > @ ( \w+ ) \ { ( \w+ ) , ( ? < kvp > \W* ( [ a-zA-Z ] + ) = \ { ( .+ ) \ } , ) ( ? & kvp ) * ( \W* ( [ a-zA-Z ] + ) = \ { ( .+ ) \ } ) \W*\ } , ? \s* ) ( ? & entry ) * | Recursive regex : Unrecognized grouping construct |
C# | Possible Duplicate : C # , int or Int32 ? Should I care ? Please any one let me know MSIL of System.Int32 and int will be same or different , If different then which one we should use.Edit : this wo n't compilebut this will | public enum MyEnum : Int32 { AEnum = 0 } public enum MyEnum : int { AEnum = 0 } | MSIL of System.Int32 and int will be same ? |
C# | I am using EnumerateFiles to get all *.md in the directory : I have three test files a.md , b.md and c.md.Now when I rename a.md to a1.md , EnumerateFiles returns both old and new filename.. The result from PowerShell says I have 3 files , while EnumerateFiles returns 4 files.I read somewhere EnumerateFiles does some k... | foreach ( var mdName in Directory.EnumerateFiles ( Path.Combine ( BaseDirectory , `` assets/markdowns '' ) , `` *.md '' , SearchOption.AllDirectories ) ) { // async md parser call goes here } [ 0 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\a.md '' [ 1 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\De... | EnumerateFiles to avoid caching |
C# | I am about to undertake a conversion of Identity 's Microsoft.AspNet.Identity.EntityFramework project ( v 2.0.0.0 ) to one that uses NHibernate as its persistence machine . My first 'stumbling block ' is this set of repositories in the UserStore class : Type parameter TUser is constrained to IdentityUser < TKey , TUser... | private readonly IDbSet < TUserLogin > _logins ; private readonly EntityStore < TRole > _roleStore ; private readonly IDbSet < TUserClaim > _userClaims ; private readonly IDbSet < TUserRole > _userRoles ; private EntityStore < TUser > _userStore ; public virtual ICollection < TRole > Roles { get ; private set ; } publi... | Why so many repositories in ASP.NET Identity 's ` UserStore ` ? |
C# | If I have something like this : Now can you please tell me how can I create a unit test that will ensure that the method generates correct xml ? How can I mock XDocument ( I am using Moq ) , without adding additional parameters to the method call | static class ManifestGenerator { public static void GenerateManifestFile ( ) { var doc = new XDocument ( ) ; ... ... xml stuff added to doc ... doc.Save ( manifestFilePath ) } | How do you mock object in a static method |
C# | it has a property : string Codeand 10 other.common codes is list of strings ( string [ ] ) cars a list of cars ( Car [ ] ) filteredListOfCars is List.Unfortunately this piece of methodexecutes too long.I have about 50k recordsHow can I lower execution time ? ? | for ( int index = 0 ; index < cars.Length ; index++ ) { Car car = cars [ index ] ; if ( commonCodes.Contains ( car.Code ) ) { filteredListOfCars.Add ( car ) ; } } | How to optimize this code |
C# | In a web project , I 'm trying to execute the following query : With breakpoints , I can see I attached to @ value0 the value , 2.Despite this , I get the following error : No value given for one or more required parameters.I understood this error is usually generated due to bad SQL syntax . Is there anything wrong wit... | SELECT ItemName as Name , ItemPicture as Picture , ItemHeroModif as Assistance , ItemTroopModif as Charisma , HerbCost as Herbs , GemCost as GemsFROM Item WHERE ItemId = @ value0 var madeForCommand = `` SELECT ItemName as Name , ItemPicture as [ Picture ] , ItemHeroModif as Assistance , ItemTroopModif as Charisma , Her... | Access SQL query missing more required parameters |
C# | Consider this silly program that does nothing : This shows that A2 and C2 implement both I < A1 > and I < A2 > , and that B2 implements both I < B1 > and I < B2 > .However , modifying this toshows that on the first and third lines , f 's generic type argument can not be inferred from the passed argument , yet on the se... | interface I < out T > { } class A1 : I < A1 > { } class A2 : A1 , I < A2 > { } class B1 { } class B2 : B1 , I < B2 > { } class C1 : I < A1 > { } class C2 : C1 , I < A2 > { } static class Program { static void f < T > ( I < T > obj ) { } static void Main ( ) { f < A1 > ( new A2 ( ) ) ; f < A2 > ( new A2 ( ) ) ; f < B1 >... | Generic type inference with multiply-implemented covariant interfaces , how to work around it ? |
C# | The following code compiles : However , when switching to an aliased using , there is a problem with the Include function , which is an extension method : The Include function can still be used , but not as an extension method . Is there any way to use it as an extension method without un-aliasing the using directive ? | using Microsoft.SharePoint.Clientclass Dummy ( ) { void DummyFunction ( ClientContext ctx , ListCollection lists ) { Context.Load ( lists , lc = > lc.Include ( l = > l.DefaultViewUrl ) ; } } using SP = Microsoft.SharePoint.Clientclass DummyAliased ( ) { void DummyFunction ( SP.ClientContext ctx , SP.ListCollection list... | C # : Extension Methods not accessible with aliased using directive |
C# | Let 's say I have these bytes : And I want to turn it into the six-character string hex representation you see in CSS ( e.g . `` # 0000ff '' ) : How can I do this ? | byte red = 0 ; byte green = 0 ; byte blue = 255 ; | C # /CSS : Convert bytes to CSS hex string |
C# | I am creating a generic class to hold widgets and I am having trouble implementing the contains method : Error : Operator '== ' can not be applied to operands of type ' V ' and ' V'If I can not compare types , how am I to implement contains ? How do dictionaries , lists , and all of the other generic containers do it ?... | public class WidgetBox < A , B , C > { public bool ContainsB ( B b ) { // Iterating thru a collection of B 's if ( b == iteratorB ) // Compiler error . ... } } | Can Not Compare Generic Values |
C# | I 'm basically wondering how I should , in C # , catch exceptions from asynchronous methods that are waited on through the await keyword . Consider for example the following small console program , which most importantly contains a method called AwaitSync . AwaitSync calls TestAsync , which returns a Task that when exe... | class Program { static void Main ( string [ ] args ) { AwaitAsync ( ) ; Console.ReadKey ( ) ; } static async Task AwaitAsync ( ) { try { await TestAsync ( ) ; } catch ( Exception ) { Console.WriteLine ( `` Exception caught '' ) ; } } static Task TestAsync ( ) { return Task.Factory.StartNew ( ( ) = > { throw new Excepti... | How do I catch in C # an exception from an asynchronous method that is awaited ? |
C# | I 've been programming in JAVA and C all my years at Uni , but now I 'm learning C # and building a small application , and I 've found troubles with this : I get a red underline for this conditional , and I do n't really know why , because according to what I 've seen that should be ok , but it is not . Is there somet... | if ( taxonType.Equals ( null ) ¦¦ taxonID == -1 ) | Conditional or in C # |
C# | Since immutable data strucutures are first-class values we can compare them for equality or order as we do with any other values . But things became complicated in BCL immutable collections preview because every immutable collection can be parameterized by IEqualityComparer < T > /IComparer < T > instances . Looks like... | var xs = ImmutableList < string > .Empty.Add ( `` AAA '' ) .WithComparer ( StringComparer.OrdinalIgnoreCase ) ; var ys = ImmutableList < string > .Empty.Add ( `` aaa '' ) .WithComparer ( StringComparer.Ordinal ) ; Console.WriteLine ( xs.Equals ( ys ) ) ; // trueConsole.WriteLine ( ys.Equals ( xs ) ) ; // false | BCL Immutable Collections : equality is non-symmetric |
C# | Ok ! I have same code written in Java and C # but the output is different ! Output : Class A . It is in C # .But when same code was ran in Java , the output was Class B . Here is the Java Code : So , why this is showing different results ? I do know that , in Java , all methods are virtual by default that 's why Java o... | class A { public void print ( ) { Console.WriteLine ( `` Class A '' ) ; } } class B : A { public void print ( ) { Console.WriteLine ( `` Class B '' ) ; } } class Program { static void Main ( string [ ] args ) { A a = new B ( ) ; a.print ( ) ; Console.Read ( ) ; } } class A { public void print ( ) { System.out.println (... | Java Vs C # : Java and C # subclasses with method overrides output different results in same scenario |
C# | My question is how to return a list of MergeObj when joining the two tables . I tried : But QueryJoin ( ) gives Exception : System.NotSupportedException , Joins are not supported . please note I 'm using sqlite.net not ADO.net . | class TableObj1 { public string Id { get ; set ; } public string Name { get ; set ; } } class TableObj2 { public string Id { get ; set ; } public string Email { get ; set ; } } class MergeObj { public TableObj1 Obj1 { get ; set ; } public TableObj2 Obj2 { get ; set ; } } public IEnumerable < MergeObj > QueryJoin ( ) { ... | How to return Wrapper obj of TableOjb1 and TableObj2 using linq |
C# | I was working with bit shift operators ( see my question Bit Array Equality ) and a SO user pointed out a bug in my calculation of my shift operand -- I was calculating a range of [ 1,32 ] instead of [ 0,31 ] for an int . ( Hurrah for the SO community ! ) In fixing the problem , I was surprised to find the following be... | -1 < < 32 == -1 -1 < < 32 == 0 | C # bit shift : is this behavior in the spec , a bug , or fortuitous ? |
C# | I have a model : and a View Model : My view has an instance of ProductViewModel as the DataContext . The view has the field : By default , validation occurs on the IDataErrorProvider of the bound object ( Product ) , not the DataContext ( ProductViewModel ) . So in the above instance , ProductViewModel validation is ne... | public class Product { public int Rating { get ; set ; } ... } public class ProductViewModel : IDataErrorProvider { public int Temperature { get ; set ; } public Product CurrentProduct { get ; set ; } public string this [ string columnName ] { get { if ( columnName == `` Rating '' ) { if ( CurrentProduct.Rating > Tempe... | IDataErrorInfo calling bound object rather than DataContext |
C# | I have a Visual Studio extension that adds an property to the property grid of a project item . It is done by registering an extender provider like this : It works fine for C # and VB projects , but only for those ... Is it possible to make it work for all project types ? If not , where can I find the CATIDs of other p... | void RegisterExtenderProvider ( ) { var provider = new PropertyExtenderProvider ( _dte , this ) ; string name = PropertyExtenderProvider.ExtenderName ; RegisterExtenderProvider ( VSConstants.CATID.CSharpFileProperties_string , name , provider ) ; RegisterExtenderProvider ( VSConstants.CATID.VBFileProperties_string , na... | Register an extender provider for all project types |
C# | I have the below code and I 'm expecting a different result.I have excepted that following result : 100 ,110 ,120 , 200 , 500Console output ( real result ) I 'm wondering now about this +1 from where came ? | using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication11 { public class Program { static void Main ( string [ ] args ) { var values = new List < int > { 100 , 110 , 120 , 200 , 500 } ; // In my mind the result shall be like ( 100,0 ) = > 100 + 0 = 100 // In my mind the result... | Unexpected results in Linq query always + 1 |
C# | C # can not infer a type argument in this pretty obvious case : The JObject type clearly implements IEnumerable < KeyValuePair < string , JToken > > , but I get the following error : Why does this happen ? UPD : To the editor who marked this question as duplicate : please note how my method 's signature accepts not IEn... | public void Test < T > ( IEnumerable < KeyValuePair < string , T > > kvp ) { Console.WriteLine ( kvp.GetType ( ) .Name + `` : KeyValues '' ) ; } Test ( new Newtonsoft.Json.Linq.JObject ( ) ) ; CS0411 : The type arguments for method can not be inferred from the usage . | Generic interface type inference weirdness in c # |
C# | Because this is my first attempt at an extension method that seems quite useful to me , I just want to make sure I 'm going down the right route Called byEDIT : Some excellent suggestions coming through , exactly the sort of thing I was looking for . ThanksEDIT : I have decided on the following implementationI preferre... | public static bool EqualsAny ( this string s , string [ ] tokens , StringComparison comparisonType ) { foreach ( string token in tokens ) { if ( s.Equals ( token , comparisonType ) ) { return true ; } } return false ; } if ( queryString [ `` secure '' ] .EqualsAny ( new string [ ] { `` true '' , '' 1 '' } , StringCompa... | My first extension method , could it be written better ? |
C# | I am trying to print some information in a column-oriented way . Everything works well for Latin characters , but when Chinese characters are printed , the columns stop being aligned . Let 's consider an example : Output : As one can see , the Chinese is not aligned to columns.Important note : this is just a presentati... | var latinPresentation1 = `` some text '' .PadRight ( 30 ) + `` | `` + 23 ; var latinPresentation2 = `` some longer text '' .PadRight ( 30 ) + `` | `` + 23 ; Console.WriteLine ( latinPresentation1 ) ; Console.WriteLine ( latinPresentation2 ) ; Console.WriteLine ( `` ... ... ... ... ... ... ... ... ... ... ... ... ... ..... | How do I format Chinese characters so they fit the columns ? |
C# | What is wrong with this code : I compile this piece of code using this command : When I double click on the exe , it does n't seem to throw the exception ( StackOverFlowException ) , and keep running forever.Using visual studio command prompt 2010 , but I also have vs 2012 installed on the system , all up to date . | using System ; namespace app1 { static class Program { static int x = 0 ; static void Main ( ) { fn1 ( ) ; } static void fn1 ( ) { Console.WriteLine ( x++ ) ; fn1 ( ) ; } } } csc /warn:0 /out : app4noex.exe app4.cs | Why does n't this recursion produce a StackOverFlowException ? |
C# | Hello I have an unusual date format that I would like to parse into a DateTime objectI would like to use DateTime.Tryparse ( ) but I cant seem to get started on this.Thanks for any help . | string date = '' 20101121 '' ; // 2010-11-21string time = '' 13:11:41 : //HH : mm : ss | How do I parse an unusual date string |
C# | Consider this code : when I call emu.ElementAt ( size-10 ) and arr.ElementAt ( size-10 ) and measure the time the arr is much faster ( the array is 0.0002s compared to IEnumerable 0.59s ) . As I understand it , the extention method ElementAt ( ) have the signature and since the 'source ' is a IEnumerable the logic carr... | int size = 100 * 1000 * 1000 ; var emu = Enumerable.Range ( 0 , size ) ; var arr = Enumerable.Range ( 0 , size ) .ToArray ( ) ; public static TSource ElementAt < TSource > ( this IEnumerable < TSource > source , int index ) | Understanding the extension ElementAt ( index ) |
C# | Looking at the code : Looking at the `` Do stuff here '' section : What type of objects can I write in there so they can be Transactionable ? . I already know that I can write ADO commands and they will be rollback/commited when neccesary . But via C # POV : what implementation should a Class has to have in order to be... | class MyClass { public static int g=1 ; } using ( TransactionScope tsTransScope = new TransactionScope ( ) ) { //Do stuff here MyClass.g=999 ; tsTransScope.Complete ( ) ; } | Transactionable objects in C # ? |
C# | I am using a Parallel.ForEach in this way : I am wondering if when paramIeCollection is empty , the Parallel.ForEach starts anyway and take threads from Thread Pool and consumes resources or if it first checks if there are items in the collection.If it does n't check , to avoid that , I am thinking in this code : So th... | public void myMethod ( IEnumerable < MyType > paramIeCollection ) { Parallel.Foreach ( paramIeCollection , ( iterator ) = > { //Do something } ) ; } if ( paramIeCollection.count > 0 ) { //run Parallel.Foreach } | Does Parallel.ForEach start threads if the source is empty ? |
C# | I have been wondering whether it would be worth implementing weak events ( where they are appropriate ) using something like the following ( rough proof of concept code ) : Allowing other classes to subscribe and unsubscribe from events with the more conventional C # syntax whilst under the hood actually being implemen... | class Foo { private WeakEvent < EventArgs > _explodedEvent = new WeakEvent < EventArgs > ( ) ; public event WeakEvent < EventArgs > .EventHandler Exploded { add { _explodedEvent += value ; } remove { _explodedEvent -= value ; } } private void OnExploded ( ) { _explodedEvent.Invoke ( this , EventArgs.Empty ) ; } public ... | Is it a good idea to implement a C # event with a weak reference under the hood ? |
C# | I have encountered an interesting situation where I get NRE from Uri.TryCreate method when it 's supposed to return false.You can reproduce the issue like below : I guess it 's failing during the parse , but when I try `` http : A '' for example , it returns true and parses it as relative url . Even if fails on parse i... | Uri url ; if ( Uri.TryCreate ( `` http : Ç '' , UriKind.RelativeOrAbsolute , out url ) ) { Console.WriteLine ( `` success '' ) ; } | Why Uri.TryCreate throws NRE when url contains Turkish character ? |
C# | I am working with WPF+MVVM.I have a VM which contains a Customer property . The Customer has an ObservableCollection of Orders . Each Order has an ObservableCollection of Items . Each Items has a Price.Now , I have the following property on my VM : The problem is whenever a change occurs at any point in this graph of o... | public double TotalPrice { return Customer.Orders.Sum ( x = > x.Items.Sum ( y = > y.Price ) ) ; } | MVVM property depends on a graph of objects |
C# | If I implement an interface for a value type and try to cast it to a List of it 's interface type , why does this result in an error whereas the reference type converts just fine ? This is the error : Can not convert instance argument type System.Collections.Generic.List < MyValueType > to System.Collections.Generic.IE... | public interface I { } public class T : I { } public struct V : I { } public void test ( ) { var listT = new List < T > ( ) ; var listV = new List < V > ( ) ; var listIT = listT.ToList < I > ( ) ; //OK var listIV = listV.ToList < I > ( ) ; //FAILS to compile , why ? var listIV2 = listV.Cast < I > ( ) .ToList ( ) ; //OK... | Why does ToList < Interface > not work for value types ? |
C# | I 'm trying to write a really simple bit of async code . I have a void method that does n't take any parameters , which is to be called from a Windows service . I want to kick it off async , so that the service does n't have to hang around waiting for the method to finish.I created a very simple test app to make sure I... | using System ; using System.Threading ; namespace AsyncCallback { internal class Program { private static void Main ( string [ ] args ) { Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - About to ask for stuff to be done '' ) ; new Action ( DoStuff ) .BeginInvoke ( ar = > StuffDone ( ) , nu... | Why does n't this C # 4.0 async method get called ? |
C# | I 'd like to write a method which does some work and finally returns another method with the same signature as the original method . The idea is to handle a stream of bytes depending on the previous byte value sequentially without going into a recursion . By calling it like this : To handover the method I want to assig... | MyDelegate executeMethod = handleFirstByte //What form should be MyDelegate ? foreach ( Byte myByte in Bytes ) { executeMethod = executeMethod ( myByte ) ; //does stuff on byte and returns the method to handle the following byte } Func < byte , Func < byte , < Func < byte , etc ... > > > | How do I declare a Func Delegate which returns a Func Delegate of the same type ? |
C# | My C # skills are low , but I ca n't understand why the following fails : Then the code is as follows : Am I simply doing something wrong and not seeing it ? Since Order implements Quotable , a list of order would go in as IList of quoatables . I have something like in Java and it works , so I 'm pretty sure its my lac... | public interface IQuotable { } public class Order : IQuotable { } public class Proxy { public void GetQuotes ( IList < IQuotable > list ) { ... } } List < Order > orders = new List < Orders > ( ) ; orders.Add ( new Order ( ) ) ; orders.Add ( new Order ( ) ) ; Proxy proxy = new Proxy ( ) ; proxy.GetQuotes ( orders ) ; /... | C # generics and interfaces and simple OO |
C# | I am currently working on an multiplayer shooter game . Basicly atm you play as a cube and you have your hand ( red square ) following the cursor ingame . I want to restrict the cursor movement to a perfect circle around my player sprite.See attached picture for clarification . https : //imgur.com/TLliade Following scr... | public class Handscript : MonoBehaviour { void Update ( ) { Cursor.visible = false ; Vector3 a = Camera.main.ScreenToWorldPoint ( new Vector3 ( Input.mousePosition.x , Input.mousePosition.y , 0 ) ) ; a.Set ( a.x , a.y , transform.position.z ) ; transform.position = Vector3.Lerp ( transform.position , a , 1f ) ; } } //H... | Restricting cursor to a radius around my Player |
C# | The code inspection of Resharper suggests to use var in C # instead of explicit type pretty much everywhere . I do n't like that option because too much var makes things unclear so I 've disabled that option . However where i do like to use var is in cases of initializations with two times the type on the same line wit... | Dictionary < string string > dic = new Dictionary < string , string > ( ) ; // I want a suggestion to replace this tovar dic = new Dictionary < string , string > ( ) ; // but I do n't want to replace things like this : Person p = new Person ( ) ; Dictionary < $ type1 $ , $ type2 $ > $ id $ = new Dictionary < $ type1 $ ... | Resharper custom pattern var |
C# | In the code below , the `` Console.WriteLine '' call needs the `` System '' using directive to work . I already have a UsingDirectiveSyntax object for `` using System '' and an InvocationExpressionSyntax object for `` Console.Writeline '' . But how can I know , using Roslyn , that the InvocationExpressionSyntax and Usi... | using System ; public class Program { public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; } } | Find UsingDirectiveSyntax that belongs to InvocationExpressionSyntax |
C# | I have the following codeI have these SubA and SubB classes which inherits from Base class , you can see that i have a code that repeating it self which is setting the Time , is there a way to move the setting of the time to the base class ? | internal abstract class Base { public DateTime Time ; public string Message ; public string Log ; public abstract void Invoke ( string message ) ; } internal class SubA : Base { public override void Invoke ( string message ) { Time = DateTime.Now ; // Do A } } internal class SubB : Base { public override void Invoke ( ... | Abstract class , how to avoid code duplication ? |
C# | I 'm having a problem withWhen the DoSomething gets executed , it receives the latest value for each captured variable instead of the value I desired . I can imagine a solution for this , but it imagine you guys can come up with better solutions | foreach ( var category in categories ) { foreach ( var word in words ) { var waitCallback = new WaitCallback ( state = > { DoSomething ( word , category ) ; } ) ; ThreadPool.QueueUserWorkItem ( waitCallback ) ; } } | How to avoid captured variables ? |
C# | Given the following class : I am torn apart between two ways to chain those constructors : The first one : The second one : So , is it better to chain from the parameterless constructor or the other way around ? | public class MyClass { private string _param ; public MyClass ( ) { _param = string.Empty ; } public MyClass ( string param ) { _param = param ; } } public MyClass ( ) : this ( string.Empty ) { } public MyClass ( string param ) { _param = param ; } public MyClass ( ) { _param = string.Empty ; } public MyClass ( string ... | In C # , what is the best/accepted way of doing constructor chaining ? |
C# | What is the correct term/name for the following construction : | string myString = ( boolValue==true ? `` true '' : `` false '' ) ; | What is the name of this code construction : condition ? true_expression : false_expression |
C# | I have a website containing news stories . Each story has a list of tags associated with it . Other pages on the site also have a list of tags.On one of the other pages I want to list all the news stories that have one or more tags in common with the list of tags on the current page.I have written some Linq code that c... | query = query.Where ( x = > x.Tags.Contains ( currentTag ) ) ; | Using Linq to compare a list with a set of lists in C # |
C# | Let me preface this by saying , I am noob , and I know not what I do . So , if there is a better way of doing this , I am all ears . Currently , I am working on project for which I need to be able to coerce a data source into a List < T > , where T is an anonymous type , and filter it using lambda expressions , or crea... | using System ; using System.Collections.Generic ; using System.Linq.Expressions ; using ExpressionBuilder.Generics ; using ExpressionBuilder.Common ; using System.Linq ; using System.Linq.Dynamic ; using System.Linq.Dynamic.Core ; using ExpressionBuilterTest.TestImplementations ; namespace ExpressionBuilterTest { class... | How to handle casting delegate of anonymous type < T > , to delegate of T for use in Where < T > ( ) method of an IEnumerable < T > |
C# | I want to know what is purpose of '\ ' in vb ? I have this statement : and I want to convert it to C # .Please suggest . | frontDigitsToKeep \ 2 | \ operator in VB |
C# | I have a centralized StructureMap configuration that various user interface applications append to . I have never had the need to modify the `` core '' configuration only append to it . I 've run into an instance today where I need to modify / remove the core configuration for a particular application . Of course I cou... | ObjectFactory.Initialize ( cfg = > { cfg.Scan ( scan = > { scan.Assembly ( `` Core '' ) ; scan.WithDefaultConventions ( ) ; scan.ConnectImplementationsToTypesClosing ( typeof ( IValidationRule < > ) ) ; // more after this ... . } } ObjectFactory.Model.For ( typeof ( IValidationRule < > ) ) .EjectAndRemoveAll ( ) ; //no... | How can I modify a previously configured StructureMap configuration ? |
C# | I do n't have very much background regarding COM nor coclasses , so I do n't quite understand why I can use the new operator with an interface . From a language/framework-agnostic view , it 's confusing why this compiles and runs correctly : Inspecting Application in Visual Studio 2010 shows me : What is going on behin... | using Microsoft.Office.Interop.Excel ; public class ExcelProgram { static void Main ( string [ ] args ) { Application excel = new Application ( ) ; } } using System.Runtime.InteropServices ; namespace Microsoft.Office.Interop.Excel { // Summary : // Represents the entire Microsoft Excel application . [ Guid ( `` 000208... | Why is it possible to create a new instance of a COM interface ? |
C# | It seems these two declarations are the same : andBut what is the need of this part new int [ ] in the second sample ? Does it make difference ? | int [ ] array1 = { 11 , 22 , 33 } ; int [ ] array2 = new int [ ] { 11 , 22 , 33 } ; | What is difference between these two array declarations ? |
C# | I created a very simple event publisher and it looks like this.Here is what I have to publish messages.The issue I 'm having is that publishing a message is n't finding any handlers that can handle the payload . This makes sense because I registered my subscribers as Func < IHandle > instead of Func < IHandle < T > > .... | public class EventPublisher { private readonly IList < Func < IHandle > > _subscribers ; public EventPublisher ( IList < Func < IHandle > > subscribers ) { _subscribers = subscribers ; } public void Publish < TPayload > ( TPayload payload ) where TPayload : class { var payloadHandlers = _subscribers.OfType < Func < IHa... | Is it possible to use an open generic as constructor argument ? |
C# | I have a method , shown below , which calls a service.How can I run this method through thread ? | public List < AccessDetails > GetAccessListOfMirror ( string mirrorId , string server ) { List < AccessDetails > accessOfMirror = new List < AccessDetails > ( ) ; string loginUserId = SessionManager.Session.Current.LoggedInUserName ; string userPassword = SessionManager.Session.Current.Password ; using ( Service1Client... | can a method with return type as list be called from a thread |
C# | Edit : fixed several syntax and consistency issues to make the code a little more apparent and close to what I actually am doing.I 've got some code that looks like this : where the DoSomething method is an extension method , and it expects a Func passed into it . So , each of the method calls in each of the DoSomethin... | SomeClass someClass ; var finalResult = DoSomething ( ( ) = > { var result = SomeThingHappensHere ( ) ; someClass = result.Data ; return result ; } ) .DoSomething ( ( ) = > return SomeOtherThingHappensHere ( someClass ) ) .DoSomething ( ( ) = > return AndYetAnotherThing ( ) ) .DoSomething ( ( ) = > return AndOneMoreThi... | Abuse of Closures ? Violations of various principles ? Or ok ? |
C# | I have a struct like this , with an explicit conversion to float : I can convert a TwFix32 to int with a single explicit cast : ( int ) fix32But to convert it to decimal , I have to use two casts : ( decimal ) ( float ) fix32There is no implicit conversion from float to either int or decimal . Why does the compiler let... | struct TwFix32 { public static explicit operator float ( TwFix32 x ) { ... } } | Why do I need an intermediate conversion to go from struct to decimal , but not struct to int ? |
C# | I have a number , for example 1234567897865 ; how do I max it out and create 99999999999999 ? I did this this way : what would be the better , proper and shorter way to approach this task ? | int len = ItemNo.ToString ( ) .Length ; String maxNumString = `` '' ; for ( int i = 0 ; i < len ; i++ ) { maxNumString += `` 9 '' ; } long maxNumber = long.Parse ( maxNumString ) ; | How to get the maximum number of a particular length |
C# | which is better ? ? ? or | public class Order { private double _price ; private double _quantity ; public double TotalCash { get { return _price * _quantity ; } } public class Order { private double _totalCash ; private double _price ; private double _quantity ; private void CalcCashTotal ( ) { _totalCash = _price * _quantity } public double Pri... | do you put your calculations on your sets or your gets . |
C# | Say I have a simple ( the simplest ? ) C # program : If , I compile that code and look at the resultant .exe , I see the `` Hello , world '' string in the exe image as expected.If I refactor the code to : If I compile that code and look at the resultant .exe , I see the `` Hello , world '' string literal in the exe ima... | class Program { static void Main ( ) { System.Console.WriteLine ( `` Hello , world '' ) ; } } class Program { const string Greeting = `` Hello , world '' ; static void Main ( ) { System.Console.WriteLine ( Greeting ) ; } } | String constants embedded twice in .Net ? |
C# | I wish to programatically unsubscribe to an event , which as been wired up.I wish to know how I can unsubscribe to the EndRequest event.I 'm not to sure how to do this , considering i 'm using inline code . ( is that the correct technical term ? ) I know i can use the some.Event -= MethodName to unsubscribe .. but I do... | public void Init ( HttpApplication httpApplication ) { httpApplication.EndRequest += ( sender , e ) = > { if ( some logic ) HandleCustomErrors ( httpApplication , sender , e , ( HttpStatusCode ) httpApplication.Response.StatusCode ) ; } ; httpApplication.Error += ( sender , e ) = > HandleCustomErrors ( httpApplication ... | How can I unsubscribe to this .NET event ? |
C# | I 'm having a bit of performance problem with an EF query.We basically have this : Now , I would like to do : The problem is that , from what I can gather , this first causes the entire list being fetched , and then the count of it . When doing this in a loop this creates a performance problem.I assumed that it was due... | public class Article { public int ID { get ; set ; } public virtual List < Visit > Visits { get ; set ; } } public class Visit { public int ? ArticleID { get ; set ; } public DateTime Date { get ; set ; } } Article a = ... ; vm.Count = a.Visits.Count ; | How to get count of lazy list in most efficient way ? |
C# | I want to do something like this : However , I can not write a function like this : This does n't work , for some reason one can not use ref and params at the same time . Why so ? edit : OK , here 's some more information on why I need this : Through an Interface I get a lot of strings containing values , with a syntax... | double a , b , c , d , e ; ParseAndWrite ( `` { 1 , 2 , 3 } '' , ref a , ref b , ref c ) ; ParseAndWrite ( `` { 4 , 5 } '' , ref d , ref e ) ; - > a = 1 , b = 2 , c = 3 , d = 4 , e = 5 private void ParseAndWrite ( string leInput , params ref double [ ] targets ) { ( ... ) } inputConfig : `` step , stepHeight , rStep , ... | Why ca n't I pass a various numbers of references to a function ? |
C# | I have this asynchronous request : The problem is that I do n't know how to run it synchronously . Please help . | Pubnub pn = new Pubnub ( publishKey , subscribeKey , secretKey , cipherKey , enableSSL ) ; pn.HereNow ( `` testchannel '' , res = > //does n't return a Task { //response } , err = > { //error response } ) ; | Pubnub perform sync request |
C# | I am rewriting some code ( targeting .NET 4.5.2. currently ) that uses reflection to compile for .NET Standard 1.4 . I therefore need to use GetTypeInfo ( ) on a Type at many places . In order to handle the edge cases correctly , my question is , can GetTypeInfo ( ) ever return null ? The documentation ( https : //msdn... | public static class IntrospectionExtensions { public static TypeInfo GetTypeInfo ( this Type type ) { if ( type == null ) { throw new ArgumentNullException ( `` type '' ) ; } var rcType= ( IReflectableType ) type ; if ( rcType==null ) { return null ; } else { return rcType.GetTypeInfo ( ) ; } } } | Can GetTypeInfo ever return null ? |
C# | So I have to design a class that works on a collection of paired objects . There is a one-to-one mapping between objects . I expect the client of the class to have established this mapping before using my class.My question is what is the best way to allow the user of my class to give me that information ? Is it to ask ... | MyClass ( IEnumerable < KeyValuePair < Object , Object > > objects ) MyClass ( IEnumberable < Object > x , IEnumerable < Object > y ) | What is the most inuitive way to ask for objects in pairs ? |
C# | I 'm creating a tree structure that is based on an AbstractNode class . The AbstractNode class has a generic collection property that contain its child nodes . See the code example below.Is there some way , possibly using generics , that I can restrict a concrete version of AbstractNode to only allow one type of child ... | public abstract class AbstractNode { public abstract NodeCollection < AbstractNode > ChildNodes { get ; set ; } } public class ConcreteNodeA : AbstractNode { //THIS DOES NOT COMPLILE //Error 1 'ConcreteNodeA.ChildNodes ' : type must be 'NodeCollection < AbstractNode > ' //to match overridden member 'AbstractNode.ChildN... | How can I restrict the children of nodes in a tree structure |
C# | I have a type and want to create an instance of it with test data . I know that frameworks like NBuilder or AutoFixture can create instances of types that are known on design time ( < T > ) . Are those frameworks able to create an instance based on a type that is only known at runtime ( Type ) ? On the end I want to do... | var value = Builder.Create ( type ) ; var constant = Expression.Constant ( value , type ) ; | Is there a way of creating an instance of a type with test data ? |
C# | Here is my string : www.stackoverflow.com/questions/ask/user/endI split it with / into a list of separated words : myString.Split ( '/ ' ) .ToList ( ) Output : and I need to rejoin the string to get a list like this : I think about linq aggregate but it seems it is not suitable here . I want to do this all through linq | www.stackoverflow.comquestionsaskuserend www.stackoverflow.comwww.stackoverflow.com/questionswww.stackoverflow.com/questions/askwww.stackoverflow.com/questions/ask/userwww.stackoverflow.com/questions/ask/user/end | Split and then Joining the String step by step - C # Linq |
C# | I 'm curious about the difference below two example.case 1 ) locking by readonly objectcase2 ) locking by target object itselfare both cases thread-safe enough ? i 'm wondering if garbage collector changes the address of list variable ( like 0x382743 = > 0x576382 ) at sometime so that it could fail thread-safe . | private readonly object key = new object ( ) ; private List < int > list = new List < int > ; private void foo ( ) { lock ( key ) { list.add ( 1 ) ; } } private List < int > list = new List < int > ; private void foo ( ) { lock ( list ) { list.add ( 1 ) ; } } | locking by target object self |
C# | First of all , I 'm new to both WCF services and dropzone JS , but I 'm trying to combine the two to create a simple image uploader . I 've got my WCF working correctly for the metadata that I 've uploaded to through it ( so I know it 's passing things cross domain correctly ) , but the Stream that I 've captured from ... | data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAAOYAAADbCAMAAABOUB36AAAAwFBMVEX ... LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5T1RUV0I1RFZZdTVlM2NTNQ0KQ29udG ... < div class= '' col-lg-12 '' > < form action= '' http : //localhost:39194/ImageRESTService.svc/AddImageStream/ '' class= '' dropzone '' id= '' dropzone '' > < /form ... | Dropzone JS Upload to WCF Getting Wrong Data |
C# | I have the following simplified code for pulling existing 8x10 PDFs from multiple locations , rotating them if need be ( almost all need to be ) , then writing them to a single 11x17 PDF page by page ... However the page rendered does n't have the pages rotated as they should be , I 've verified the height > width bran... | while ( Page < StackOne.Length ) { Files++ ; using ( var strm = new FileStream ( RenderPath + `` Test_ '' + Page + `` .pdf '' , FileMode.Create , FileAccess.Write , FileShare.Read ) ) { using ( var MasterReport = new iTextSharp.text.Document ( iTextSharp.text.PageSize._11X17 ) ) { using ( var writer = PdfWriter.GetInst... | Rotate multiple PDFs and write to one single PDF |
C# | To be honest I was n't sure how to word this question so forgive me if the actual question is n't what you were expecting based on the title . C # is the first statically typed language I 've ever programmed in and that aspect of it has been an absolute headache for me so far . I 'm fairly sure I just do n't have a goo... | abstract class DataMold < T > { public abstract T Result { get ; } } class TextMold : DataMold < string > { public string Result = > `` ABC '' ; } class NumberMold : DataMold < int > { public int Result = > 123 } List < DataMold < T > > molds = new List < DataMold < T > > ( ) ; molds.Add ( new TextMold ( ) ) ; molds.Ad... | How do I properly work with calling methods on related but different classes in C # |
C# | I have a ParseTree listener implementation that I 'm using to fetch global-scope declarations in standard VBA modules : Is there a way to tell the tree walker to stop walking ? Say I have a VBA module like this : I would like the tree walker to stop walking the parse tree as soon as it enters Public Sub DoSomething ( )... | public class DeclarationSectionListener : DeclarationListener { private bool _insideProcedure ; public override void EnterVariableStmt ( VisualBasic6Parser.VariableStmtContext context ) { var visibility = context.visibility ( ) ; if ( ! _insideProcedure & & visibility == null || visibility.GetText ( ) == Tokens.Public ... | Can a walker be stopped ? |
C# | The ProblemOur company make specialized devices running Windows XP ( Windows XPe , to be precise ) . One of the unbending legal requirements we face is that we must quickly detect when a fixed IDE drive is removed . Quickly as in within a few seconds.The drives in question are IDE drives . They are also software-protec... | Kernel32.CreateFile ( filename , File_Access.GenericRead | File_Access.GenericWrite , File_Share.Read | File_Share.Write , IntPtr.Zero , CreationDisposition.CreateAlways , CreateFileFlagsAndAttributes.File_Attribute_Hidden | CreateFileFlagsAndAttributes.File_Attribute_System , IntPtr.Zero ) ; Kernel32.FlushFileBuffers ... | Quickly detect removal of fixed IDE drive in Windows XP |
C# | The following code works : So naturally you 'd think that this code would work too : But I get the error Invalid cast operation - does anybody know why that might happen ? UPDATE tblStocks is a list of LINQ to SQL object , tblStock.JsonStock is a simplified version of the tblStock class and gets returned to a webpage a... | List < JsonStock > stock = new List < JsonStock > ( ) ; foreach ( tblStock item in repository.Single ( id ) .tblStocks ) stock.Add ( ( JsonStock ) item ) ; List < JsonStock > stock = repository.Single ( id ) .tblStocks.Cast < JsonStock > ( ) .ToList ( ) public partial class tblStock { public static explicit operator Js... | Casting List < x > to List < y > |
C# | Could anyone tell me why these two modulus calculations yield two different outcomes ? I just need to blame someone or something but me for all those hours I lost finding this bug.Using VS-2017 V15.3.5 | public void test1 ( ) { int stepAmount = 100 ; float t = 0.02f ; float remainder = t % ( 1f / stepAmount ) ; Debug.Log ( `` Remainder : `` + remainder ) ; // Remainder : 0.01 float fractions = 1f / stepAmount ; remainder = t % fractions ; Debug.Log ( `` Remainder : `` + remainder ) ; // Remainder : 0 } | Modulus gives wrong outcome ? |
C# | This is driving me crazy . I have been looking for the source of the issue for hours , but i am starting to suspect this is not an issue in my logic ... Maybe i am wrong.Issue descriptionI have a simple Entry . Its Text property is bound to a property with type double in a ViewModel . At the same time i subscribe to th... | if ( double.TryParse ( entry.Text , out double result ) ) { entry.Text = String.Format ( `` { 0 : F2 } '' , result ) ; } < StackLayout > < Entry Text= '' { Binding Weight } '' Unfocused= '' entry_Unfocused '' / > < /StackLayout > public partial class MainPage : ContentPage { public MainPage ( ) { InitializeComponent ( ... | Setter of property bound to Entry.Text loops infinitely |
C# | I have this query to collection : This gets only the Panel that has an hyperlink with a certain id . I need to get not only the firstOrDefault but the matched element ( only the first ) and the 2 next within the sequence . I did n't try anything because do n't know how . | Panel thePanel = menuCell.Controls.OfType < Panel > ( ) .Where ( panel = > panel.Controls.OfType < HyperLink > ( ) .Any ( label = > label.ID == clas ) ) .FirstOrDefault ( ) ; | How to get an element range in linq within a sequence ? |
C# | I confuse between double [ ] [ ] and double [ , ] in C # .My teammate give me a function like this : I want to use this function : It lead an error : invalid argument.I do n't want to edit my teammate 's code.Does it have any way to convert double [ ] [ ] to double [ , ] ? Thanks ! | public double [ ] [ ] Do_Something ( double [ ] [ ] A ) { ... ... . } double [ , ] data = survey.GetSurveyData ( ) ; //Get datadouble [ , ] inrma = Do_Something ( data ) ; | C # : double [ ] [ ] and double [ , ] |
C# | I have a question on something I 've never seen before in C # . In the service provider in the new asp.net dependency injection , there is a method with return _ = > null ; https : //github.com/aspnet/DependencyInjection/blob/dev/src/Microsoft.Framework.DependencyInjection/ServiceProvider.csLines 63-72.The method in qu... | private Func < MyServiceProvider , object > CreateServiceAccessor ( Type serviceType ) { var callSite = GetServiceCallSite ( serviceType , new HashSet < Type > ( ) ) ; if ( callSite ! = null ) { return RealizeService ( _table , serviceType , callSite ) ; } return _ = > null ; } | What is the return _ in C # |
C# | EDIT : I 'm considering this question different from the potential duplicate because none of the answers on that one contain the approach I went with which is the BitConverter class . In case me marking this as not a duplicate gets rid of the potential duplicate question link here it is.I 'm wondering what the c # equi... | byte offsetdata [ sizeof ( int ) ] = { 0,0,0,0 } ; offsetdata [ 0 ] = m_Response [ responseIndex++ ] ; offsetdata [ 1 ] = m_Response [ responseIndex++ ] ; offsetdata [ 2 ] = m_Response [ responseIndex++ ] ; offsetdata [ 3 ] = m_Response [ responseIndex++ ] ; int offset = 0 ; memcpy ( & offset , offsetdata , sizeof offs... | What is the C # equivalent of memcpy array to int ? |
C# | I have a singleton that can register a func to resolve an id value for each type : for example : and then i want to resolve the id for an object , like these : where GetObjectId definition isThe question is , how can i store a reference for each func to invoke it lately.The problem is that each func has a different T t... | public void RegisterType < T > ( Func < T , uint > func ) RegisterType < Post > ( p = > p.PostId ) ; RegisterType < Comment > ( p = > p.CommentId ) ; GetObjectId ( myPost ) ; public uint GetObjectId ( object obj ) private Dictionary < Type , Func < object , uint > > _typeMap ; | references to Func 's of different types |
C# | I am writing an API that connects to a service which either returns a simple `` Success '' message or one of over 100 different flavors of failure.Originally I thought to write the method that sends a request to this service such that if it succeeded the method returns nothing , but if it fails for whatever reason , it... | try { ChargeCreditCard ( cardNumber , expDate , hugeAmountOMoney ) ; } catch ( ChargeFailException e ) { // client handles error depending on type of failure as specified by specific type of exception } var status = TryChargeCreditCard ( cardNumber , expDate , hugeAmountOMoney ) ; if ( ! status.wasSuccessful ) { // cli... | Best Practice way to indicate that a server request has failed ? |
C# | Say I have a Repository class which has a DbContext . In this class I have a method : In a Service class I use this method to create an object : And finally in my api controller MyObjectController I return this object like so : I 'm confused about all these async and await keywords . I know that a Task is awaitable . D... | public async Task < T > CreateAsync ( T obj ) { var o = _dbSet.Add ( obj ) ; await _dbContext.SaveChangesAsync ( ) ; return o ; } public async Task < MyObject > Create ( ) { return await _repository.CreateAsync ( new MyObject ( ) ) ; } public async Task < IHttpActionResult > Get ( ) { return Ok ( await _service.Create ... | When should you await a Task ? |
C# | I 'm not quite sure of the different betweenandBoth worked exactly the same , why would I need to change it to an _ like shown ? IMAGE OF THE `` POTENTIAL FIX '' | DataTable itemTable = new DataTable ( ) ; itemTable = //CODE _ = new DataTable ( ) ; DataTable itemTable = //CODE | C # Use discard ' _ ' |
C# | For the long time I thought I get it , and I was going to create some puzzles to learn some of my „ students “ on the topic of operator precedence in c # .But it came out that I still do n't get it right . Puzzles : What ’ s the output here ? Output : -20All clear here , I expected thisNext , the problem one : Output ... | int a = 0 ; int x = -- a + a++ ; Console.WriteLine ( x ) ; Console.WriteLine ( a ) ; int b = 0 ; int y = b -- + b++ ; Console.WriteLine ( y ) ; Console.WriteLine ( b ) ; | ++ -- Operator precedence puzzle |
C# | I am looking for a solution in LINQ but anything helps ( C # ) . I tried using Sort ( ) but its not working for example i have a sample list that contains the response I get is : and what I want is : any idea on a good unit test for this method ? just to text that it is getting sorted that way . | { `` a '' , `` b '' , `` f '' , `` aa '' , `` z '' , `` ac '' , `` ba '' } a , aa , ac , b , ba , f , z a , b , f , z , aa , ac , ba . | C # Sorting alphabetical order a - z and then to aa , ab - zz |
C# | I created an application that stores byte arrays in my SQLiteDatabase.This same application also selects the byte arrays from the database every ' x ' seconds . The dataflow of my application is as follow : Application - > SQLiteDatabase - > ApplicationMy question is : How do I fill one byte array with all the incoming... | Byte [ ] Data ; Byte [ ] IncomingData ; | Filling one byte [ ] with multiple byte [ ] s |
C# | I have 2 ListViews and a TextBlock . The first ListView1 includes letters in Alphabetical order . And the second ListView2 includes the words that start with the selected letter ( in ListView1 ) . When I choose a letter from ListView1 and then click on a word loaded in ListView2 , I want to get the definition of this w... | < ListView Width= '' 510 '' x : Name= '' ListView1 '' ItemsSource= '' { Binding } '' Background= '' White '' Foreground= '' Black '' TabIndex= '' 1 '' Margin= '' -7,8,0,0 '' IsSwipeEnabled= '' False '' SelectionChanged= '' ItemListView_SelectionChanged '' Grid.Row= '' 1 '' HorizontalAlignment= '' Left '' > < ListView.I... | Can not set SelectedIndex= '' 0 '' in Xaml to ListView ( Windows Store App ) |
C# | Are there any overheads to using the following sytax : As opposed to : When I was learning VB6 , I was told doing the quivelent in VB had an overhead - is the same true in .NET ? | Form1 myForm = new Form1 ( ) ; myForm.Show ( ) ; Form1 myForm ; myForm = new Form1 ( ) ; myForm.Show ( ) ; | C # Object Declarations |
C# | I have a thread that spins until an int changed by another thread is a certain value.Does this.m_cur need to be declared volatile for this to work ? Is it possible that this will spin forever due to compiler optimization ? | int cur = this.m_cur ; while ( cur > this.Max ) { // spin until cur is < = max cur = this.m_cur ; } | Do I need this field to be volatile ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.