lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | How can I sort a list based on a pre-sorted list . I have a list which is already sorted . Say , my sorted list is Now , I want to sort any subset of the above list in the same order as the above list . That is , if I have as input { `` Developer '' , `` Junior Developer '' } , I want the output as { `` Junior Develope... | { `` Junior Developer '' , `` Developer '' , `` Senior Developer '' , `` Project Lead '' } { `` Junior Developer '' , `` Developer '' , `` Project Lead '' } . | Sort a List based on a Pre-Sorted List |
C# | I am trying to do is to get filepath for my excel file . But I am unable to do so.File is in Document/Visual Studio 2013/Project/ProjectName/a.xlsxIs it wrong way to do it or is it correct way ? | string path = Path.Combine ( HttpContext.Current.Server.MapPath ( `` ~/ '' ) , '' a.xlsx '' ) ; string SheetName= '' Sheet1 '' ; | Get FilePath for my excel file with sheetname |
C# | I am using Activiz.NET to render some STLs in a C # tool . The renderwindow and renderer settings are as follows.Running the tool on an STL on my system results in the following image ( which is as expected ) . ( Click image for full size ) However , when two of my colleagues run the same tool on the exact same STL , t... | window.SetMultiSamples ( 0 ) ; window.SetAlphaBitPlanes ( 1 ) ; renderer.SetOcclusionRatio ( 0.1 ) ; renderer.SetUseDepthPeeling ( 1 ) ; | VTK ( Activiz ) rendering differently on different hardware |
C# | Let me show you part of my XAML code : When too much borders are created ( it is linked with an ObservableCollection ) , a vertical scroll bar appears , and my border does n't resize on its own . ( I would like to see the complete border , I don t want it to be cut at the end ) If anyone has an idea , thanks ! Do n't h... | < ListBox Grid.Row= '' 1 '' ScrollViewer.HorizontalScrollBarVisibility= '' Disabled '' ScrollViewer.IsDeferredScrollingEnabled= '' True '' HorizontalAlignment= '' Stretch '' ItemsSource= '' { Binding } '' Margin= '' 1,1,0,0 '' Name= '' listBox_Faits '' Width= '' 290 '' VerticalAlignment= '' Stretch '' SelectionChanged=... | Resize my border when a VerticalScrollBar appear |
C# | Consider the following code : Anything wrong with this approach ? Is there a more appropriate way to build an array , without knowing the size , or elements ahead of time ? | List < double > l = new List < double > ( ) ; //add unknown number of values to the listl.Add ( 0.1 ) ; //assume we do n't have these values ahead of time.l.Add ( 0.11 ) ; l.Add ( 0.1 ) ; l.ToArray ( ) ; //ultimately we want an array of doubles | Efficiency : Creating an array of doubles incrementally ? |
C# | I came across following code and do n't know what does having from twice mean in this code . Does it mean there is a join between Books and CSBooks ? | List < Product > Books = new List < Product > ( ) ; List < Product > CSBooks = new List < Product > ( ) ; var AllBooks = from Bk in Books from CsBk in CSBooks where Bk ! = CsBk select new [ ] { Bk , CsBk } ; | does using `` from '' more than once is equivalent to have join ? |
C# | In spite of the RFC stating that the order of uniquely-named headers should n't matter , the website I 'm sending this request to does implement a check on the order of headers.This works : This does n't work : The default HttpWebRequest seems to put the Host and Connection headers at the end , before the blank line , ... | GET https : //www.thewebsite.com HTTP/1.1Host : www.thewebsite.comConnection : keep-aliveAccept : */*User-Agent : Mozilla/5.0 etc GET https : //www.thewebsite.com HTTP/1.1Accept : */*User-Agent : Mozilla/5.0 etcHost : www.thewebsite.comConnection : keep-alive | Strict ordering of HTTP headers in HttpWebrequest |
C# | We know all types inherit Equals from their base class , which is Object.Per Microsoft docs : Equals returns true only if the items being compared refer to the same item in memory.So we use Equals ( ) to compare object references , not the state of the object . Typically , this method is overridden to return true only ... | Employee A=New Employee ( ) ; Employee B=New Employee ( ) ; A.SSN=B.SSN ; A.LiceneNumber=B.LiceneNumber ; | What does .NET 's Equals method really mean ? |
C# | I have a struct that has a field called typeHow do i access it in F # ? c # f # How do i access the type field of A ? | struct A { int type ; } let a = A ( ) let myThing = a.type //error because type is a reserved keyword | access .Net field from F # when the field name is a reserved keyword |
C# | I wrote this quickly under interview conditions , I wanted to post it to the community to possibly see if there was a better/faster/cleaner way to go about it . How could this be optimized ? | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Stack { class StackElement < T > { public T Data { get ; set ; } public StackElement < T > Below { get ; set ; } public StackElement ( T data ) { Data = data ; } } public class Stack < T > { private StackElement < T > to... | See any problems with this C # implementation of a stack ? |
C# | I have this code : How can I access a property of test object ? When I put a breakpoint , visual studio can see the variables of this object ... Why ca n't I ? I really need to access those . | object test = new { a = `` 3 '' , b = `` 4 '' } ; Console.WriteLine ( test ) ; //I put a breakpoint here | Accessing anonymous type variables |
C# | I have the following code : However it returns different results whether it 's compiled from VS2012 or VS2015 ( both have `` standard '' settings ) In VS2012In VS2015 : VS2012 dissasembly : VS2015 dissasembly : As we can see the disassembly is not identical in both cases , is this normal ? Could this be a bug in VS2012... | float a = 0.02f * 28f ; double b = ( double ) a ; double c = ( double ) ( 0.02f * 28f ) ; Console.WriteLine ( String.Format ( `` { 0 : F20 } '' , b ) ) ; Console.WriteLine ( String.Format ( `` { 0 : F20 } '' , c ) ) ; 0,560000002384186000000,55999998748302500000 0,560000002384186000000,56000000238418600000 float a = 0.... | difference of float/double conversion betwen VS2012 and VS2015 |
C# | This code results in the following output : GetDistinctValuesUsingWhere No1 : 1,2,3,4 GetDistinctValuesUsingWhere No2 : GetDistinctValuesUsingForEach No1 : 1,2,3,4 GetDistinctValuesUsingForEach No2 : 1,2,3,4I do n't understand why I do n't get any values in the row `` GetDistinctValuesUsingWhere No2 '' . Can anyone exp... | using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication { internal class Program { public static void Main ( ) { var values = new [ ] { 1 , 2 , 3 , 3 , 2 , 1 , 4 } ; var distinctValues = GetDistinctValuesUsingWhere ( values ) ; Console.WriteLine ( `` GetDistinctValuesUsingWher... | Where vs. foreach with if - why different results ? |
C# | I have the following List : which after populating the list I end up with the following data : I have multiple SKU 's as the item can be supplied from more then one Warehouse location as it 's in stock . In the case of SKU001 , warehouse ID 2 has more stock than warehouse ID 3.I need to select the items from the least ... | public class Products { public string SKU ; public int WarehouseID ; } List < Products > products = new List < Products > ( ) ; ProductCode|WarehouseIDSKU001|2SKU001|3SKU002|3SKU003|3SKU004|1SKU004|5 SKU001|3SKU002|3SKU003|3SKU004|1 products.GroupBy ( i = > i ) .OrderByDescending ( grp = > grp.Count ( ) ) .Select ( grp... | Selecting values from List |
C# | I have a web application which is supposed to be composed as a series of plugins into a core infrastructure . A plugin is a compiled CLR dll + some content files which will be put in a certain location . I 'm using Autofac to scan and register types out of the assembly , and some fancy routing to serve controllers and ... | ApplyMigrations < MyDbContext , MyDbConfiguration > ( ) ; Database.SetInitializer ( ... ) | EF multi-context with a plugin-style system . How to apply migrations at runtime ? |
C# | First of all I have to specify that I 'm working in Unity 5.3 and the new MonoDevelop does n't allow me to debug . Unity just crashes : ( So I have a list of `` goals '' that I need to sort based on 3 criterias : first should be listed the `` active '' goalsthen ordered by difficulty levelfinally randomly for goals of ... | public class Goal { public int ID ; public int Level ; public bool Active ; } ... List < Goal > goals ; goals.Sort ( ( a , b ) = > { // first chooses the Active ones ( if any ) var sort = b.Active.CompareTo ( a.Active ) ; if ( sort == 0 ) { // then sort by level sort = ( a.Level ) .CompareTo ( b.Level ) ; // if same le... | What is wrong with my sorting ? |
C# | I have a some small doubt with classes and objects . In a class I have 10 to 20 methods , ( shared below ) When creating a object for the above class . How many methods will be stored in memory ? Only the calling method or all the methods.Can you please help me on the above scenario . | public class tstCls { public void a1 ( ) { } void a2 ( ) { } void a3 ( ) { } void a4 ( ) { } void a5 ( ) { } void a6 ( ) { } void a7 ( ) { } void a8 ( ) { } void a9 ( ) { } } static void Main ( string [ ] args ) { tstCls objcls = new tstCls ( ) ; objcls.a1 ( ) ; } | How many methods in a class will be created in memory when an object is created in C # ? |
C# | Disclaimer : I would love to be using dependency injection on this project and have a loosely coupled interface-based design across the board , but use of dependency-injection has been shot down in this project . Also SOLID design principles ( and design patterns in general ) are something foreign where I work and I 'm... | // Foo is a class that wraps underlying functionality from another // assembly to create a simplified API . Think of this as a service layer class , // a facade-like wrapper . It contains a helper class that is specific to// foo . Other AbstractFoo implementations have their own helpers.public class Foo : AbstractFoo {... | Is there a better design option ? |
C# | I am reading `` The D Programming Language '' by Andrei Alexandrescu and one sentence puzzled me . Consider such code ( p.138 ) : and call ( p.140 ) : Explanation ( paragraph below the code ) : If we squint hard enough , we do see that the intent of the caller in this case was to have T = double and benefit from the ni... | T [ ] find ( T ) ( T [ ] haystack , T needle ) { while ( haystack.length > 0 & & haystack [ 0 ] ! = needle ) { haystack = haystack [ 1 .. $ ] ; } return haystack ; } double [ ] a = [ 1.0 , 2.5 , 2.0 , 3.4 ] ; a = find ( a , 2 ) ; // Error ! ' find ( double [ ] , int ) ' undefined | What is wrong with inferred type of template and implicit type conversion ? |
C# | We are not forced to fill the returned value from e.g . a method call into a declared variable of expected type , but what happens to it in that situation ? Where does the following returned value go/What happens to it : ? Obviously , if I wanted to see the result from the method call I would do the following : ( This ... | decimal d = 5.5m ; Math.Round ( d , MidpointRounding.AwayFromZero ) ; decimal d = 5.5m ; decimal d2 = Math.Round ( d , MidpointRounding.AwayFromZero ) ; // Returns 6 into // the variable `` d2 '' | Where does the returned value from e.g . a method call go if not filled into a declared variable of expected type ? |
C# | I am using JwtBearer authentication to secure my API . I am adding [ Authorize ] above each API and it worked . I am using this code to add the authentication in the startup : I want a way to add the [ Authorize ] to a function in a service , or write a code in the function that works the same as [ Authorize ] . | services.AddAuthentication ( `` Bearer '' ) .AddJwtBearer ( `` Bearer '' , options = > { options.Authority = `` http : //localhost:1234 '' ; options.RequireHttpsMetadata = false ; options.Audience = `` test '' ; } ) ; | ASPNet Core : Use [ Authorize ] with function in service |
C# | I have a strange situation that I ca n't duplicate consistently . I have a MVC website developed in .NET Core 3.0 and authorizes users with .NET Core Identity . When I run the site in a development environment locally everything works just fine ( the classic `` works on my machine ! '' ) . When I deploy it to my stagin... | public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } public IWebHostEnvironment Env { get ; set ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServ... | Ajax Calls Return 401 When .NET Core Site Is Deployed |
C# | I think I 've developed a cargo-cult programming habit : Whenever I need to make a class threadsafe , such as a class that has a Dictionary or List ( that is entirely encapsulated : never accessed directly and modified only by member methods of my class ) I create two objects , like so : In this case , I wrap all opera... | public static class Recorder { private static readonly Object _devicesLock = new Object ( ) ; private static readonly Dictionary < String , DeviceRecordings > _devices ; static Recorder ( ) { _devices = new Dictionary < String , DeviceRecordings > ( ) ; WaveInCapabilities [ ] devices = AudioManager.GetInDevices ( ) ; f... | Cargo-cult programming : locking on System.Object |
C# | I 'm experimenting with WeakReference , and I 'm writing a code that checks if a weak reference is valid before returning a strong reference to the object.How should I prevent the GC collecting the object between the `` IsValid '' and the `` Target '' calls ? | if ( weakRef.IsValid ) return ( ReferencedType ) weakRef.Target ; else // Build a new object | Block garbage collector while analyzing weak references |
C# | I have base class for my entitiesI have to use this strange construction Entity < T > where T : Entity < T > , because i want static method FromXElement to be strongly-typedAlso , i have some entities , like thatHow can i create a generic list of my entities , using base class ? | public class Entity < T > where T : Entity < T > , new ( ) { public XElement ToXElement ( ) { } public static T FromXElement ( XElement x ) { } } public class Category : Entity < Category > { } public class Collection : Entity < Collection > { } var list = new List < Entity < ? > > ( ) ; list.Add ( new Category ( ) ) ;... | Create list of generics |
C# | I want to retrieve values from a tree stored in another system . For example : To avoid typing errors and invalid keys , I want to check the name at compile time by creating an object or class with the tree structure in it : Is there an easy way to do this in C # without creating classes for each tree node ? Can I use ... | GetValue ( `` Vehicle.Car.Ford.Focus.Engine.Oil.Color '' ) GetValue ( Vehicle.Car.Ford.Focus.Engine.Oil.Color ) | Compile time tree structure |
C# | I want to replace string which is a square bracket with another number . I am using regex replace method.Sample input : This is [ test ] version.Required output ( replacing `` [ test ] '' with 1.0 ) : This is 1.0 version.Right now regex is not replacing the special character . Below is the code which I have tried : The... | string input= `` This is [ test ] version of application . `` ; string stringtoFind = string.Format ( @ '' \b { 0 } \b '' , `` [ test ] '' ) ; Console.WriteLine ( Regex.Replace ( input , stringtoFind , `` 1.0 '' ) ) ; | Word boundaries not matching when the word starts or ends with special character like square brackets |
C# | I am having the following preudo-codewhere the entire code has , let 's say 500 lines with lots of logic inside for statements . The problem is refactoring this into a readable and maintainable code and as a best practice for similar situations . Here are the possible solutions I found so far.1 : Split into methodsCons... | using ( some web service/disposable object ) { list1 = service.get1 ( ) ; list2 = service.get2 ( ) ; for ( item2 in list2 ) { list3 = service.get3 ( depending on item2 ) ; for ( item3 in list3 ) { list4 = service.get4 ( depending on item3 and list1 ) ; for ( item4 in list4 ) { ... } } } } for ( item2 in list2 ) { compu... | Refactoring inner loops with lots of dependencies between levels |
C# | I want to create an instance of FormsAuthenticationTicket ( over which I have no control , part of System.Web.Security ) using Autofixture AND making sure that the UserData ( of type string ) contains a valid XML stringThe problem is that UserData can only be set when instantiating the object using the following constr... | var testTicket = fixture.Create < FormsAuthenticationTicket > ( ) ; public FormsAuthenticationTicket ( int version , string name , DateTime issueDate , DateTime expiration , bool isPersistent , string userData ) ; | Create an instance of FormsAuthenticationTicket with a valid XML string in UserData |
C# | Variables : Current If statementQuestion : Instead of having multiple if statements , for each variable . How can I create 1 if statement to go through all these variables ? Something like this : | private string filePath1 = null ; private string filePath2 = null ; private string filePath3 = null ; private string filePath4 = null ; private string filePath5 = null ; private string filePath6 = null ; private string filePath7 = null ; private string filePath8 = null ; private string filePath9 = null ; private string... | If statement with multiple variables ending with a number |
C# | I 'm trying to diagnose issues updating Google Fusion Tables using CSV data via the API . Everything seems to work correctly code side of things with no errors reported but the data does not reflect the changes . Any ideas how I can diagnose what is going wrong ? I 've been using the Google.Apis.Fusiontables.v2 C # lib... | fusiontablesService.Table.ReplaceRows ( tableId , stream , `` application/octet-stream '' ) .Upload ( ) ; | Diagnosing Google Fusion Table update using API to upload CSV issue |
C# | Let 's think of it as a family tree , a father has kids , those kids have kids , those kids have kids , etc ... So I have a recursive function that gets the father uses Recursion to get the children and for now just print them to debug output window ... But at some point ( after one hour of letting it run and printing ... | private void MyLoadMethod ( string conceptCKI ) { // make some script calls to DB , so that moTargetConceptList2 will have Concept-Relations for the current node . // when this is zero , it means its a leaf . int numberofKids = moTargetConceptList2.ConceptReltns.Count ( ) ; if ( numberofKids == 0 ) return ; for ( int i... | Does creating new Processes help me for Traversing a big tree ? |
C# | I can automatically register all types that implement interfaces with this statementHow can I specify a namespace for interfaces and implementations ? i.e : only interfaces in Framework.RepositoryInterfaces should get resolved by types in Framework.RepositoryImplementations . | IUnityContainer container = new UnityContainer ( ) ; container.RegisterTypes ( AllClasses.FromAssembliesInBasePath ( ) , WithMappings.FromMatchingInterface , WithName.Default , WithLifetime.Transient ) ; ICustomer result = container.Resolve < ICustomer > ( ) ; | Resolve dependencies only from specified namespace |
C# | i 've got a disordered file with 500000 line which its information and date are like the following : Now how can i implement such a thing ? I 've tried the sortedList and sorteddictionary methods but there is no way for implemeting a new value in the list because there are some repetative values in the list . I 'd appr... | for instance desired Result -- -- -- -- -- -- -- -- -- -- -- -- -- - 723,80 1,4 14,50 1,5 723,2 10,8 1,5 14,50 10,8 723,2 1,4 723,80 | How can I sort the file txt line 5000000 ? |
C# | When you have nested co-routines like Is the StartCoroutine in yield return StartCoroutine ( Bar ( ) ) ; necessary ? Are we allowed to just do If we are allowed , does this have any impact on the program behavior/performance ? | void Update ( ) { if ( someTest ) { StartCoroutine ( Foo ( ) ) ; } } IEnumerator Foo ( ) { doStuff = true ; yield return StartCoroutine ( Bar ( ) ) ; doStuff = false ; } IEnumerator Bar ( ) { //Very important things ! } void Update ( ) { if ( someTest ) { StartCoroutine ( Foo ( ) ) ; } } IEnumerator Foo ( ) { doStuff =... | Is a StartCoroutine needed for a call from inside one co-routine to another co-routine ? |
C# | I just spent hours being confused by an NullReferenceException where I thought there should n't be one . I was constructing a class like so : whereBasically my IL was the following : and I finally figured that it must be that bar was not being instantiated . I constructed my class in C # and compiled it and found the o... | public class MyClass : MyBase < Foo > { public MyClass ( ) { base.Method ( Foo.StaticField ) ; } } public class MyBase < T > { private SomeObject bar = new SomeObject ( ) ; public void Method ( object o ) { this.bar.AnotherMethod ( o ) ; // exception thrown here } } ctorIl.Emit ( OpCodes.Ldarg_0 ) ; ctorIl.Emit ( OpCod... | Why do we need to explicitly call parent constructor in MSIL ? |
C# | I 've created a Generic Class to parse some data into another instance of a class ( MyClass1 ) . Since MyClass1 has only built-in C # types , my GenericMethod works fine . The problem starts to grow when MyClass1 has another MyClass2 property and I still want to invoke my GenericMethod to parse my data.I ca n't trigger... | public class MyClass1 { public int MyIntProperty { get ; set ; } public string MyStringProperty { get ; set ; } public MyClass2 MyClass2Property { get ; set ; } } public class MyClass2 { public int MyOtherIntProperty { get ; set ; } public string MyOtherStringProperty { get ; set ; } public bool MyOtherBoolProperty { g... | How to trigger a Generic Class method recursively changing the type of T ? |
C# | I have this loop : But instead I would like to have i for just numbers 1,2,4,5 and 7 and I will hardcode this.Is there a way I can do this with something like an array ? | for ( int i = 1 ; i < 10 ; i++ ) | Is there a way to code a for loop so that it does n't increment through a sequence ? |
C# | It seems I 'm running into more woes with 'my most favorite datatype ' SqlDecimal.I 'm wondering if this should be considered a bug or not.When I multiply two small numbers in SQL I get the expected result . When I run the same numbers through a SQLCLR function the results are , well surprising.c # code : SQL Code : Th... | using System.Data.SqlTypes ; using Microsoft.SqlServer.Server ; namespace TestMultiplySQLDecimal { public static class Multiplier { [ SqlFunction ( DataAccess=DataAccessKind.None , IsDeterministic = true , IsPrecise = true ) ] public static SqlDecimal Multiply ( SqlDecimal a , SqlDecimal b ) { if ( a.IsNull || b.IsNull... | c # SqlDecimal flipping sign in multiplication of small numbers |
C# | I am trying to setup a ESRI Local Server for displaying .mpk . I have a Model likein ViewModel.cs Class I haveAs you can see I am trying to implement the local server and dynamic layer in ViewModel.cs like but I do not know how to bind this service to the Model ? I tried but as you know the myModel does n't have any Ma... | public class Model { private string basemapLayerUri = `` http : //services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer '' ; private string mapPackage = `` D : \\App\\Data\\Canada.mpk '' ; public Model ( ) { } public string BasemapLayerUri { get { return this.basemapLayerUri ; } set { if ( value ! = t... | Implementing MVVM with ArcGIS Runtime local server |
C# | Here is demonstration of the problem : This become an issue if there are methods with many parameters ( e.g . ten of double type ) : Question : is there a way to validate parameters when calling method , so that programmer is less prone to do a mistake ? This is not an issue if parameter types are different . I thought... | class Program { static double Func ( double a , double b ) { return a * 1000 + b * b ; } static void Main ( string [ ] args ) { var a = 1.1d ; var b = 2.2d ; Console.WriteLine ( Func ( a , b ) ) ; // this is the problem , function does n't recognize when a and b // `` accidentally '' exchanged , target is to make this ... | Compile-time method call validation for multiple parameters of the same type |
C# | I met with the strange behavior of the generic . Below is the code I use for testing.Output : I found it very strange that the second Console.WriteLine call displays a class , not an interface , because I use a generic type definition . Is this correct behaviour ? I 'm trying to implement generic type inference in my c... | public static class Program { public static void Main ( ) { Type listClassType = typeof ( List < int > ) .GetGenericTypeDefinition ( ) ; Type listInterfaceType = listClassType.GetInterfaces ( ) [ 0 ] ; Console.WriteLine ( listClassType.GetGenericArguments ( ) [ 0 ] .DeclaringType ) ; Console.WriteLine ( listInterfaceTy... | Generic strange behaviour |
C# | A question related to the C # /.NET compiler used in Visual Studio 2010 : During the development of a project , a colleague encountered a situation where the VS2010 compiler would crash when using existing code inside a lock . We took the code apart line-by-line to eventually come to the conclusion that using a yield r... | using System ; using System.Collections.Generic ; namespace PlayGround { public static class Program { private static readonly object SyncRoot = new object ( ) ; private static IEnumerable < int > EnumerableWithLock ( ) { lock ( SyncRoot ) { foreach ( var i in new int [ 1 ] ) { yield return i ; } } } public static void... | Why does a yield in a foreach-iteration through an array within a lock crash the VS2010 compiler ? |
C# | I 'm using an API where , unfortunately , calling a get property accessor has a side-effect . How can I ensure that : is n't optimized away by the compiler ? | public void Foo ( ) { var x = obj.TheProp ; // is it guarnateed to be accessed ? } | Ensure statement is not optimized `` away '' |
C# | I started off by reading through this suggested question similar to mine , but there was no resolution : Why does MSTest.TestAdapter adds its DLLs into my NuGet package ? Quick Problem DescriptionI wrote a NuGet package , and each time I install it , NUnit and NUnit3TestAdapter .dll 's get added to the project I instal... | Install-Package C : \Path\To\client-library-repro-nuget-issue\ClientLibrary\ClientLibrary.1.0.0.nupkg nunit.engine.api.dllnunit.engine.dllNUnit3.TestAdapter.dllNUnit3.TestAdapter.pdb < ? xml version= '' 1.0 '' ? > < package > < metadata > < id > ClientLibrary < /id > < version > 1.0 < /version > < title > Client Librar... | Can I work around adding these .dlls when installing NuGet package ? |
C# | Is there a property / method in Serilog where I could ( programmatically ) check the current configuration ? ( sinks , minimum level ) e.g . if have this config : How could I read this config later ? ( In my case the config is dynamically created outside my application ) | Log.Logger = new LoggerConfiguration ( ) .MinimumLevel.Debug ( ) .WriteTo.File ( `` log.txt '' ) .WriteTo.Console ( restrictedToMinimumLevel : LogEventLevel.Information ) .CreateLogger ( ) ; | Read current Serilog 's configuration |
C# | I 've create a SPROC that saves an object and returns the id of the new object saved . Now , I 'd like to return an int not an int ? Thanks for helping | public int Save ( Contact contact ) { int ? id ; context.Save_And_SendBackID ( contact.FirstName , contact.LastName , ref id ) ; //How do I return an int instead of an int ? } | How do I convert int ? into int |
C# | I have seen that is is possible to add compiled methods together . Does it make sense to do this ? I would intend to use the filter in place of a lambda expression to filter a repository of customers : Depending on business logic , I may or may not add the three compiled methods together , but pick and choose , and pos... | Expression < Func < Customer , bool > > ln = c = > c.lastname.Equals ( _customer.lastName , StringComparison.InvariantCultureIgnoreCase ) ; Expression < Func < Customer , bool > > fn = c = > c.firstname.Equals ( _customer.firstName , StringComparison.InvariantCultureIgnoreCase ) ; Expression < Func < Customer , bool > ... | What 's the purpose of adding compiled Func methods together ? |
C# | I 'm writing a quadtree-like data structure which contains matrices of generic objects T. If four subnodes all contain defined matrices of T , I 'm going to aggregate them into a single , larger matrix , then delete the subnodes . Is there a more efficient way to do this than looping through every reference and copying... | T [ , ] _leaf1 = new T [ 64,64 ] ; T [ , ] _leaf2 = new T [ 64,64 ] ; T [ , ] _leaf3 = new T [ 64,64 ] ; T [ , ] _leaf4 = new T [ 64,64 ] ; // Populate leafsT [ , ] _root = new T [ 128,128 ] ; CopyInto ( ref _root , ref _leaf1 , 64 , 64 ) ; CopyInto ( ref _root , ref _leaf2 , 0 , 64 ) ; CopyInto ( ref _root , ref _leaf... | Efficiently copying a matrix of objects to a larger matrix of objects |
C# | I have a class that has the variable `` Magic '' . This is a 4 char string . Can I do something like this in C # ? *Assume that `` chunkList '' is an IList/List of `` chunk '' objects . | string offset = chunkList [ `` _blf '' ] .offset ; | Can I use Square Brackets to pull a value from a class |
C# | I 'm not wanting to start a flame war on micro-optimisation , but I am curious about something.What 's the overhead in terms of memory and performance of creating instances of a type that has no intrinsic data ? For example , a simple class that implements IComparer < T > may contain only a Compare method , and no prop... | class FooComprarer : IComparer < Foo > { public int Compare ( Foo x , Foo y ) { // blah , blah } } | What 's the overhead of a data-less type ? |
C# | Hey how can I detect when my ListView is scrolled up or down ? I have this : Do I need to do something with `` verticalBar.Height > verticalBar.ActualHeight '' ? | private void MainPage_OnLoaded ( object sender , RoutedEventArgs e ) { var scrollViewer = MyListView.GetFirstDescendantOfType < ScrollViewer > ( ) ; scrollViewer.ViewChanged += BarScroll ; } private void BarScroll ( object sender , ScrollViewerViewChangedEventArgs e ) { var scrollbars = ( sender as ScrollViewer ) .GetD... | Detect when ListView is scrolled `` up '' or `` down '' ? Windows Phone 8.1 ListView |
C# | I have problems with the `` order '' of the values of an enum . It 's a little difficult to explain , that 's why I wrote up some code : The output is : Enum A : TwoTwoTwoFourEnum B : ThreeThreeThreeFourEnum C : OneOneOneFourMy question is : WHY ! ? I ca n't find the logic to the output . Most of the time there is some... | class Program { public enum EnumA { One = 1 , Two = One , Three = Two , Four = 4 } public enum EnumB { One = 1 , Two = One , Four = 4 , Three = Two } public enum EnumC { Two = One , Three = Two , Four = 4 , One = 1 } static void Main ( string [ ] args ) { Console.WriteLine ( `` Enum A : '' ) ; Console.WriteLine ( EnumA... | Why ( and how ) does the order of an Enum influence the ToString value ? |
C# | I 'm missing something basic , but I ca n't figure it out . Given : Over in another class I want to allow callers to be able to RegisterFor < SpecialEvent > ( x = > { ... } ) However , the _validTypes.Add line does not compile . It can not convert a Action < T > to an Action < EventBase > . The constraint specifies tha... | abstract class EventBase { } class SpecialEvent : EventBase { } public class FooHandler { { internal Dictionary < Type , Action < EventBase > > _validTypes = new Dictionary < Type , Action < EventBase > > ( ) ; internal void RegisterFor < T > ( Action < T > handlerFcn ) where T : EventBase { _validTypes.Add ( typeof ( ... | Why is the generic parameter not casting ? |
C# | I am trying to do some charting in LinqPad . I have some logs from an api and i know , what api was called and if the request was cached ( in our real case we resolve address with coordinates from bing api or we get addres from cache table if we have cached it ) i use this linqpad script : That is the result : Actually... | var startDate = new DateTime ( 2019 , 1,1 ) ; var Requests = new [ ] { new { Date=startDate , Name = `` Api1 '' , Cached=true } , new { Date=startDate , Name = `` Api2 '' , Cached=true } , new { Date=startDate , Name = `` Api3 '' , Cached=true } , new { Date=startDate , Name = `` Api1 '' , Cached=true } , new { Date=st... | Linqpad Charting . Combination of Column and StackedColumn |
C# | While going through our client 's code , I came across below interface in C # , which is having a member with `` this '' keyword.I am not aware of any such pattern or practice where interface member name starts with `` this '' . To understand more , I checked the implementation of this interface , however still not abl... | public interface ISettings { string this [ string key ] { get ; } } internal class SettingsManager : ISettings { public string this [ string key ] { get { return ConfigurationManager.AppSettings [ key ] ; } } ... ... } public static class Utility { public static ISettings Handler { get ; set ; } public static string Ge... | Interface member with `` this '' keyword |
C# | I currently have the followingwould it be cleaner to do this ? is it safe ? | if ( ! RunCommand ( LogonAsAServiceCommand ) ) return ; if ( ! ServicesRunningOrStart ( ) ) return ; if ( ! ServicesStoppedOrHalt ( ) ) return ; if ( ! BashCommand ( CreateRuntimeBashCommand ) ) return ; if ( ! ServicesStoppedOrHalt ( ) ) return ; if ( ! BashCommand ( BootstrapDataBashCommand ) ) return ; if ( ! Servic... | c # is this design `` Correct '' ? |
C# | I have the following html helper method : I have a need to put move it to into a helper library that is structured in this way : I am unable to figure out how to structure my HelperFactory class and the EditorBuilder class constructor to handle the generics correctly.This is what I tried and it did n't work : The end g... | public static MvcHtmlString CustomEditorFor < TModel , TProperty > ( this HtmlHelper < TModel > helper , Expression < Func < TModel , TProperty > > expression , EditorOptions options , object htmlAttributes ) { } public class HtmlHelperExenion { public static Custom ( this HtmlHelper helper ) { return new HelperFactory... | Convert static method with generic paramerter to a generic class |
C# | I 'm developing an app with Entity Framework.I 've got a combo box with the names of the tables in the database.I have the following code : how can i avoid all these if-else checks ? Is it possible to get the name of a class from a string holding the name ? example : | string table = cbTables.SelectedItem.ToString ( ) ; using ( var dbContext = new Entities ( ) ) { if ( table.Equals ( `` Person '' ) ) { List < Person > list = ( from l in dbContext.People select l ) .ToList ( ) ; } else if ( table.Equals ( `` Student '' ) ) { List < Student > list = ( from u in dbContext.Student select... | Avoid a lot of if - else checks - Choose table from string using the entity framework |
C# | Can you please tell me what kind of construct in C # is this.Code Golf : Numeric equivalent of an Excel column nameThough I am new to C # ( only two months exp so far ) , but since the time I have joined a C # team , I have never seen this kind of chaining . It really attracted me and I want to learn more about it.Plea... | C.WriteLine ( C.ReadLine ( ) .Reverse ( ) .Select ( ( c , i ) = > ( c - 64 ) * System.Math.Pow ( 26 , i ) ) .Sum ( ) ) ; | What is this kind of chaining in C # called ? |
C# | I 'm trying a simple comparison here , assignment does n't work as i would like ... here is the code , I ran my debugger ( In VS ) and when that assignment is called , the int on the right was equal to 50 , but the int on the left stayed equal to 0 . No idea what I 'm missing.This application is using the Abbyy FineRea... | int returnDateIndex ( Paragraph para ) { long firstIndex = 0 ; for ( int i = 0 ; i < para.Words.Count ; i++ ) { if ( para.Words [ i ] .Text == `` Second '' ) { if ( para.Words [ i - 1 ] .Text == `` First '' ) { firstIndex = para.Words [ i ] .FirstSymbolPosition ; } } } return ( int ) firstIndex ; } | C # Noob with a question : Int assignment not working as expected |
C# | In my controller I need to call a method BlockingHttpRequest ( ) which makes an http request . It is relatively slow running , and blocks the thread.I am not in a position to refactor that method to make it async.Is it better to wrap this method in a Task.Run to at least free up a UI/controller thread ? I 'm not sure i... | public class MyController : Controller { public async Task < PartialViewResult > Sync ( ) { BlockingHttpRequest ( ) ; return PartialView ( ) ; } public async Task < PartialViewResult > Async ( ) { await Task.Run ( ( ) = > BlockingHttpRequest ( ) ) ; return PartialView ( ) ; } } | Can you increase throughput by using Task.Run on synchronous code in a controller ? |
C# | The documented derivation constraint uses a where T : clause and the sample code that I 'm tinkering with iswhere IPassClass is an interface.Code from a third-party that I am using has the formatBoth result in the same behaviour in my code , but are they the same and if not what is the difference ? | public class TwoThingsIPC < T > where T : IPassClass { ... } public class TwoThingsIPC < IPassClass > { ... } | Which is the preferred syntax for a Generic Class Derivation Constraint ? |
C# | I want a generic way to convert an asynchronous method to an observable . In my case , I 'm dealing with methods that uses HttpClient to fetch data from an API.Let 's say we have the method Task < string > GetSomeData ( ) that needs to become a single Observable < string > where the values is generated as a combination... | public class ObservableCreationWrapper < T > { private Subject < Unit > _manualCallsSubject = new Subject < Unit > ( ) ; private Func < Task < T > > _methodToCall ; private IObservable < T > _manualCalls ; public IObservable < T > Stream { get ; private set ; } public ObservableCreationWrapper ( Func < Task < T > > met... | Create observable from periodic async request |
C# | Assume i want to create an alias of a type in C # using a hypothetical syntax : Then i go away and create a few thousand files that use Currency type.Then i realize that i prefer to use FCL types : Excellent , all code still works ... .months later ... Wait , i 'm getting some strange rounding errors . Oh that 's why ,... | Currency = float ; Currency = System.Single ; Currency = System.Double ; Currency = System.Decimal ; Currency = Money ; Currency = ICurrency ; | Techniques for aliasing in C # ? |
C# | Essentially , will more memory be used by instances of Foo when its value is acquired like this : or like this ? That is , is memory used per-method per-object or per-type ? | public class Foo { internal double bar ; double GetBar ( ) { return bar ; } } public class Foo { internal double bar ; } public static class FooManager { public static double GetBar ( Foo foo ) { return foo.bar ; } } | Does it cost more memory to load classes with more methods ? |
C# | Background I am creating a custom wpf panel . To help lay out the child items it uses a secondary list ( similar to Grid.RowDefinitions or Grid.ColumnDefinitions ) that I call `` layouts '' . Each layout has a couple dependency properties , and child items use an attached property to determine where they 're placed as ... | < Panel > < Panel.Layouts > < Layout/ > < Layout Attachment= '' Right '' / > < Layout Attachment= '' Left '' Target= '' 0 '' / > < /Panel.Layouts > < ChildItem Panel.Layout= '' 0 '' / > < ChildItem Panel.Layout= '' 1 '' / > < ChildItem Panel.Layout= '' 2 '' / > < Panel/ > LayoutCollection : IList { public int IList.Add... | When do declared XAML list items have their dependency properties set ? |
C# | I have doubt about these two aspects ; First one ; Second one ; What happens if we dont assign the newly created instance to a variable and directly call the method ? I see some difference between two way on IL code.This one below is IL output of first c # codeAnd this one is the IL output of the second c # codeCould y... | Test test = new Test ( ) ; result = test.DoWork ( _param ) ; result = new Test ( ) .DoWork ( _param ) ; IL_0000 : ldstr `` job `` IL_0005 : stloc.0 IL_0006 : newobj instance void Works.Test : :.ctor ( ) IL_000b : stloc.1 IL_000c : ldloc.1 IL_000d : ldloc.0 IL_000e : callvirt instance string Works.Test : :DoWork ( strin... | Calling method of non-assigned class |
C# | Our company is switching the SMTP mail server to Office 365 . The key issue is the new SMTP server `` smtp.office365.com '' only supports TLS encryption . Thus I can not use CredentialCache.DefaultNetworkCredentials to encode my Windows log-in password automatically.Previously this works without any issue . But if I no... | var smtpClient = new SmtpClient ( `` smtp.oldserver.com '' ) { Credentials = CredentialCache.DefaultNetworkCredentials } ; const string from = `` myemail @ xyz.com '' ; const string recipients = `` myemail @ xyz.com '' ; smtpClient.Send ( from , recipients , `` Test Subject '' , `` Test Body '' ) ; var smtpClient = new... | Use DefaultNetworkCredential under TLS encryption ? |
C# | A question came up during a code review the other day about how quickly a using block should be closed . One camp said , 'as soon as you are done with the object ' ; the other , 'sometime before it goes out of scope'.In this specific example , there are a DataTable and a SqlCommand object to be disposed . We need to re... | List < MyObject > listToReturn = new List < MyObject > ( ) ; DataTable dt = null ; try { using ( InHouseDataAdapter inHouseDataAdapter = new InHouseDataAdapter ( ) ) using ( SqlCommand cmd = new SqlCommand ( ) ) { dt = inHouseDataAdapter.GetDataTable ( cmd ) ; } foreach ( DataRow dr in dt.Rows ) { listToReturn.Add ( ne... | How quickly should I close a using block ? |
C# | I want to check some locking behaviors and i ca n't understand this : I thought that this should not work due to the fact i am doing the synchronization on an integer value . First Boxing , then Unboxing and i should get a System.Threading.SynchronizationLockException because of the missing sync block root ( i know thi... | static void Main ( string [ ] args ) { for ( int i = 0 ; i < 10 ; i++ ) { Task.Factory.StartNew ( ( ) = > { MultithreadedMethod ( ) ; } ) ; } Thread.Sleep ( 2000 ) ; Console.WriteLine ( count ) ; } static int count = 0 ; private static readonly int sync = 5 ; public static void MultithreadedMethod ( ) { if ( Monitor.Tr... | Locking on a primitive type |
C# | I was all excited at writing this generic function when the compiler threw an error ( unable to cast T to System.Web.UI.Control ) I basically pass it a type when I call it , and it look for all controls of that type . The error occurs on l.Add ( ( T ) ctrl ) ; Am I missing something or am I just out of luck ? | private List < T > RecurseTypes < T > ( Control ctrls ) { var l = new List < T > ( ) ; foreach ( var ctrl in ctrls.Controls ) if ( ctrl.GetType ( ) is T ) l.Add ( ( T ) ctrl ) ; return l ; } | My first generic casting ( C # ) |
C# | I have the following code : If I compile and run this using an x86 configuration in Visual Studio , then I get the following output : If I instead compile as x64 I get this : I realize that using 32 och 64 bit compilation must affect how double values are handled by the system , but given that C # defines double as bei... | var d = double.Parse ( `` 4796.400000000001 '' ) ; Console.WriteLine ( d.ToString ( `` G17 '' , CultureInfo.InvariantCulture ) ) ; 4796.4000000000005 4796.4000000000015 var d0 = double.Parse ( `` 4796.400000000001 '' ) ; double d1 = 4796.400000000001 ; Console.WriteLine ( `` d0 : `` + d0.ToString ( `` G17 '' , CultureI... | On double parsing in C # |
C# | I am trying to retrieve a value of private property via reflectionWhere is my mistake ? I will need to use object to pass instance , because some of private properties will be declared in the A or B . And even hiding ( with new ) Base properties sometimes . | // definitionpublic class Base { private bool Test { get { return true ; } } } public class A : Base { } public class B : Base { } // nowobject obj = new A ( ) ; // or new B ( ) // worksvar test1 = typeof ( Base ) .GetProperty ( `` Test '' , BindingFlags.Instance | BindingFlags.NonPublic ) ; if ( test1 ! = null ) // it... | typeof ( ) works , GetType ( ) does n't works when retrieving property |
C# | I have these lines in my view.cshtml : But now there is a red line under ; in javascript codes and the error is Syntax error.What is the problem ? | $ ( `` document '' ) .ready ( function ( ) { @ { var cx = Json.Encode ( ViewBag.x ) ; var cy = Json.Encode ( ViewBag.y ) ; } var x = @ cx ; var y = @ cy ; } ) ; | How to fill javascript variables with c # ones ? |
C# | I 'm new to functional way of thinking in C # ( well ... not limited to language ) . Let 's say there 's method : Concept1 . ValidationWhen invalid input is given , I should return something like Either < IEnumerable < ValidationError > , T > .2 . ExecutionWhen calling DB/API/ ... which could throw , I should return Ei... | T LoadRecord < T > ( int id ) Either < IEnumerable < ValidationError > , Either < Exception , Option < T > > LoadRecord < T > ( int id ) Validation < Result < Option < T > > > LoadRecord < T > ( int id ) return LoadRecord < User > ( 1 ) .Match ( vl = > BadRequest ( ) , vr = > vr.Match ( el = > StatusCode ( 500 ) , er =... | C # FP : Validation and execution with error handling functional way - space for improvement ? |
C# | I have a query which should be ordered like that : But if any object is null ( totally by design ) this query fails.How can I put null values at the end or skip ordering if object is null ? ADDED : as @ LasseV.Karlsen mentioned I might have ANOTHER problem.I really got ArgumentNullException , but the reason was not beh... | var list = new List < MonthClosureViewModel > ( ) ; var orderedList = list .OrderByDescending ( x = > x.Project ) .ThenByDescending ( x = > x.ChargeLine ) .ThenByDescending ( x = > x.DomesticSite ) // < - x.DomesticSite might be null sometimes .ThenByDescending ( x = > x.ChargeSite ) // < - x.ChargeSite might be null s... | Skip ThenBy on nullable objects |
C# | I have to parse out the system name from a larger string . The system name has a prefix of `` ABC '' and then a number . Some examples are : the full string where i need to parse out the system name from can look like any of the items below : before I saw the last one , i had this code that worked pretty well : but it ... | ABC500ABC1100ABC1300 ABC1100 - 2pplABC1300ABC 1300ABC-1300Managers Associates Only ( ABC1100 - 2ppl ) string [ ] trimmedStrings = jobTitle.Split ( new char [ ] { '- ' , '– ' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( s = > s.Trim ( ) ) .ToArray ( ) ; return trimmedStrings [ 0 ] ; | In C # , what is the best way to parse out this value from a string ? |
C# | I 'm making a query on a MethodInfo [ ] where I 'm trying to find all the methods that have a return type of void , and has only one parameter of a certain type . I want to do it in the most minimalistic and shortest way.One way to do it would be : orBut there 's a redundant GetParameters call - One call should be enou... | var validMethods = methods.Where ( m = > m.ReturnType == typeof ( void ) & & m.GetParameters ( ) .Length == 1 & & m.GetParameters ( ) [ 0 ] .ParameterType == wantedType ) ; var validMethods = methods .Where ( m = > m.ReturnType == typeof ( void ) ) .Where ( m.GetParameters ( ) .Length == 1 & & m.GetParameters ( ) [ 0 ]... | Shorten this LINQ query via the help of an anonymous type ? |
C# | I inherited some source code that I am just starting to dig though , and i found the previous owner has made some use of the using directive as an alias for a List < T > , but I 've never seen this specific approach before.Both of these elements are used quite heavily within the code and are also return types from seve... | namespace MyNamespace { using pType1 = List < type1 > ; using pType2 = List < List < type1 > > ; // classes here } | Using Directive to declare a pseudo-type in C # |
C# | I 've developed a simple app , which just have to upload files from a folder to Azure Blob Storage , I runs fine when I run in from VS , but in the published app I get this error once in a while : ved System.IO.__Error.WinIOError ( Int32 errorCode , String , maybeFullPath ) ved System.IO.FileStream.Init ( String path ,... | private void Process ( object sender , NotifyCollectionChangedEventArgs e ) { if ( paths.Count > 0 ) { var currentPath = paths.Dequeue ( ) ; CloudStorageAccount storageAccount = CloudStorageAccount.Parse ( UserSettings.Instance.getConnectionString ( ) ) ; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClien... | IOException when uploading to Blob Storage in published app |
C# | I am reading Beginning C # to refresh my memory on C # ( background in C++ ) .I came across this snippet in the book : The snippet above will not compile - because according to the book , the variable text is not initialized , ( only initialized in the loop - and the value last assigned to it is lost when the loop bloc... | int i ; string text ; for ( i = 0 ; i < 10 ; i++ ) { text = `` Line `` + Convert.ToString ( i ) ; Console.WriteLine ( `` { 0 } '' , text ) ; } Console.WriteLine ( `` Last text output in loop : { 0 } '' , text ) ; | Variable scope in C # |
C# | I am trying to use Selenium to enter SQL code into a Code Mirror textbox . I 'll use the site http : //www.gudusoft.com/sqlflow/ # / as an example for the purposes of this question.My Problem : I am unable to submit MSSQL SQL code into the code text box if the code contains a carriage return or line feed.As a work arou... | Clipboard.SetText ( sql ) ; var txtbx = codeMirror.FindElement ( By.CssSelector ( `` textarea '' ) ) ; txtbx.Click ( ) ; txtbx.SendKeys ( OpenQA.Selenium.Keys.Control + `` v '' ) ; Selenium.Chrome.WebDriverSelenium.WebDriverSelenium.WebDriver.ChromeDriver using OpenQA.Selenium ; using OpenQA.Selenium.Chrome ; namespace... | Using C # and Selenium to enter multi lined SQL text into a Code Mirror textbox on a webpage |
C# | I have a string which contains multiple items separated by commas : As you can see some elements contain Whitespaces , My object is to remove all the whitespaces , This is my code : And this is my result : it works well , But I ask if there is another more optimized way to get the same result ? | string RESULT = `` D_CA , P_AMOUNT , D_SH , D_CU , D_TO , D_GO , D_LE , D_NU , D_CO , D_MU , D_PMU , D_DP , P_COMMENT `` ; RESULT.Split ( ' , ' ) .ToList ( ) .ForEach ( p = > if ( p.Contains ( `` `` ) ) { RESULT = RESULT.Replace ( p , p.Trim ( ) ) ; } } ) ; `` D_CA , P_AMOUNT , D_SH , D_CU , D_TO , D_GO , D_LE , D_NU ,... | Remove whitespace in elements in string C # |
C# | In an MFC program , you can determine whether the application shortcut had the Run value set to `` Minimized '' by checking the value of m_nCmdShow . Is there an equivalent way to do this in c # ? To clarify , I do n't want to set the state of a particular form . If you look at the properties for a shortcut , there is ... | [ STAThread ] static void Main ( string [ ] args ) { ProcessStartInfo processInfo = Process.GetCurrentProcess ( ) .StartInfo ; MessageBox.Show ( processInfo.WindowStyle.ToString ( ) ) ; ... } | Is there a c # equivalent of m_nCmdShow ? |
C# | This is a question similar to this one here.Is there a built-in method that converts an array of byte to hex string ? More specifically , I 'm looking for a built in function for | /// < summary > /// Convert bytes in a array Bytes to string in hexadecimal format /// < /summary > /// < param name= '' Bytes '' > Bytes array < /param > /// < param name= '' Length '' > Total byte to convert < /param > /// < returns > < /returns > public static string ByteToHexString ( byte [ ] Bytes , int Length ) {... | Builtin Function to Convert from Byte to Hex String |
C# | In this scenario what would be the value of Result if myObject is null ? | var result = myObject ? .GetType ( ) ; | C # 6 null propagation what value is set when object is null |
C# | I 'm running into a problem with the following pseudoquery : It runs but the generated SQL statement that LINQ sends to SQL Server is absurd . The actual implementation follows a similar setup as above with 7 or so more columns that each have a .Sum ( ) calculation . The generated SQL has somewhere around 10-11 nested ... | var daily = from p in db.table1 group p by new { key1 , key2 } into g join d in db.table2 on new { p.key1 , p.key2 } equals { d.key1 , d.key2 } select new { col1 = g.Key.key1 col2 = g.Sum ( a = > a.column2 ) col3 = d.column3 } ; var daily = from p in ( from p in db.table1 group p by new { key1 , key2 } into g select ne... | Two similar LINQ queries , completely different generated SQL |
C# | This question is an extension of Cristi Diaconescu 's about the illegality of field initializers accessing this in C # .This is illegal in C # : Ok , so the reasonable explanation to why this is illegal is given by , among others , Eric Lippert : In short , the ability to access the receiver before the constructor body... | class C { int i = 5 ; double [ ] dd = new double [ i ] ; //Compiler error : A field initializer can not reference the non-static field , method , or property . } | Field initializer accessing 'this ' reloaded |
C# | It is posible in C # to decide in constructor , which other override constructor use ? This below code does n't compile ! I do n't know which invocation use . | public IntRange ( int val , bool isMax ) : isMax ? this ( ) : this ( ) { if ( isMax ) { IntRange ( 0 , val ) ; } else { IntRange ( val , int.MaxValue ) ; } } | Can a constructor include logic that determines which other constructor overrides to call ? |
C# | This surprised me - the same arithmetic gives different results depending on how its executed : ( Tested in Linqpad ) What 's going on ? Edit : I understand why floating point arithmetic is imprecise , but not why it would be inconsistent.The venerable C reliably confirms that 0.1 + 0.2 == 0.3 holds for single-precisio... | > 0.1f+0.2f==0.3fFalse > var z = 0.3f ; > 0.1f+0.2f==zTrue > 0.1f+0.2f== ( dynamic ) 0.3fTrue | Floating point inconsistency between expression and assigned object |
C# | I have an iterative C # loop which fills out a checkboard pattern of up to 5 columns.The values are paired , it 's always a Headline and multiple Values for each column , and it 's combining the values to a non-repetitative combination.Starting with the simplest solution I could imagine , and after looking at it , I th... | List < EtOfferVariant > variants = new List < EtOfferVariant > ( ) ; _containers [ 0 ] .Variant.ForEach ( first = > { if ( _containers.Count > 1 ) { _containers [ 1 ] .Variant.ForEach ( second = > { if ( _containers.Count > 2 ) { _containers [ 2 ] .Variant.ForEach ( third = > { EtOfferVariant va = new EtOfferVariant ( ... | How to go from iterative approach to recursive approach |
C# | Does the ? ? operator in C # use shortcircuiting when evaluating ? When myObject is non-null , the result of ExpressionWithSideEffects ( ) is not used , but will ExpressionWithSideEffects ( ) be skipped completely ? | var result = myObject ? ? ExpressionWithSideEffects ( ) ; | Does the `` ? ? `` operator use shortcircuiting ? |
C# | This question is about static stack analysis of custom C # IL code and how to design the opcodes to satisfy the compiler.I have code that modifies existing C # methods by appending my own code to it . To avoid that the original method returns before my code is executed , it replaces all RET opcodes with a BR endlabel a... | public static string SomeMethod ( int val ) { switch ( val ) { case 0 : return `` string1 '' .convert ( ) ; case 1 : return `` string2 '' .convert ( ) ; case 2 : return `` string3 '' .convert ( ) ; // ... } return `` '' ; } .method public hidebysig static string SomeMethod ( int32 val ) cil managed { .maxstack 1 .local... | C # IL code modification - keep stack intact |
C# | I have the following method : Question is : i dont want the user to wait for csv dump , which might take a while.If i use a thread for csvdump , will it complete ? before or after the return of output ? After csvdump is finished , i d like to notify another class to process the csv file . someMethod doesnt need to wait... | public List < string > someMethod ( ) { // populate list of strings // dump them to csv file //return to output } | C # Threading in a method |
C# | i want to create a dictionary like : Why ca n't I ? | Dictionary < string , < Dictionary < string , string > > > | Why ca n't I create a dictionary < string , dictionary < string , string > > ? |
C# | In my function I receive objects implementing IMediaPanel interface : During the initialization I need to specify properties ' names , for which I 'm using C # 6.0 nameof keyword : This works fine , but with this expression : Visual Studio shows me the following error : The property 'MyNamespace.IMediaPanel.IsNextEntit... | public interface IMediaPanel { bool IsListsAreaVisible { get ; } bool IsNextEntityExists { set ; } } private void InitConnections ( IMediaPanel panelControl ) { // Initialization logic } nameof ( IMediaPanel.IsListsAreaVisible ) nameof ( IMediaPanel.IsNextEntityExists ) public void Init ( FrameworkElement panelControl ... | Using `` nameof '' keyword with set-only property |
C# | I 'm working a project to replace a Resource Management system ( QuickTime Resource Manager on Mac and Windows ) that has been deprecated and I have been using the current model that Qt uses where data is retrieved from the resource file using a string key.For example , I may have an image in my resource file , `` Hung... | image = GetImageResource ( `` BearPlugin/Images/HungryBear.png '' ) ; oldActiveResourceFile = GetActiveResourceFile ( ) ; // think of a stack of resource filesSetActiveResourceFile ( `` BearPlugin '' ) ; image = GetImageResource ( 1 ) ; // Perhaps other resources are retrieved and other functions called// Possibly intr... | Why are string identifiers used to access resource data ? |
C# | Consider the following piece of code : If you execute this , the variable en will get the value of TestEnum.BA . Now I have learned from this that enum flags should be unique , or you get these kind of unexpected things , but I do fail to understand what is happening here.The even weirder part is that when I add the [ ... | namespace ConsoleApplication1 { class Program { public static void Main ( string [ ] args ) { var en = ( TestEnum ) Enum.Parse ( typeof ( TestEnum ) , `` AA '' ) ; Console.WriteLine ( en.ToString ( ) ) ; Console.ReadKey ( ) ; } } public enum TestEnum { AA = 0x01 , AB = 0x02 , AC = 0x03 , BA = 0x01 , BB = 0x02 , BC = 0x... | Enum.Parse returning unexpected members |
C# | I am maintaining an ASP.NET MVC project . In the project the original developer has an absolute ton of interfaces . For example : IOrderService , IPaymentService , IEmailService , IResourceService . The thing I am confused about is each of these is only implemented by a single class . In other words : My understanding ... | OrderService : IOrderServicePaymentService : IPaymentService Square : IShapeCircle : IShape public class OrderService : IOrderService { private readonly ICommunicationService _communicationService ; private readonly ILogger _logger ; private readonly IRepository < Product > _productRepository ; public OrderService ( IC... | Am I confused about interfaces ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.