lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have a collection that I first need to filter and then select one out of it , but how the collection should be processed is different depending on some parameters . So I went with 2 delegates , but somehow I should combine them : I tried something like this but it fails because the delegates are n't of matching types... | delegate IEnumerable < T > FilterDelegate ( IEnumerable < T > collection ) ; delegate T SelectorDelegate ( IEnumerable < T > collection , ref T previous ) ; //Combine above two to this one : delegate T GetItemDelegate ( IEnumerable < T > collection , ref T previous ) ; static GetItemDelegate CreateDelegate ( FilterDele... | Is it possible to combine delegates of different types ( use return value as parameter ) ? |
C# | I have an immutable class that I want to write to and read from a CSV file . The issue is I am getting an exception when reading the CSV despite having mapped the object and set up a configuration that should allow this to work.To do this I am using CsvHelper . The immutable class looks like the following.I have no iss... | public class ImmutableTest { public Guid Id { get ; } public string Name { get ; } public ImmutableTest ( string name ) : this ( Guid.NewGuid ( ) , name ) { } public ImmutableTest ( Guid id , string name ) { Id = id ; Name = name ; } } public sealed class ImmutableTestMap : ClassMap < ImmutableTest > { public Immutable... | CsvHelper and immutable types |
C# | I have an interface and a typed factory interface : I Then have an implementation of another interface IDependencyOwner : IDisposable which is implementend by : The DependencyOwner is held a dependency for yet another object , and there can be many implementations of DependencyOwner , which are resolved with the Collec... | public interface ITransientItem : IDisposable { void DoWork ( WorkItem item ) ; } public interface ITransientItemFactory : IDisposable { ITransientItem Create ( ) ; void Destroy ( ITransientItem item ) ; } public class DependencyOwner : IDependencyOwner { private ITransientItemFactory _factory ; public DependencyOwner ... | TypedFactory Disposes Before Component Using it As a Dependency |
C# | I 'm a new programmer , so please excuse any dumbness of this question , how the following code is encapsulating private data ? -I mean , with no restriction logic or filtering logic in the properties , how is the above code different from the folowing one -Is the first code providing any encapsulation at all ? | public class SomeClass { private int age ; public int Age { get { return age ; } set { age = value ; } } public SomeClass ( int age ) { this.age = age ; } } public class SomeClass { public int age ; public SomeClass ( int age ) { this.age = age ; } } | Where 's the Encapsulation ? |
C# | I 'm new to C # and have run into a problem with the following code ( I have the target framework as 4.5 and I 've added a reference to System.Numerics ) : When the release build is started with debugging ( F5 in Visual Studio - and a break-point at the end of program so I can see the output ) , I get the following out... | using System ; using System.Numerics ; namespace Test { class Program { static BigInteger Gcd ( BigInteger x , BigInteger y ) { Console.WriteLine ( `` GCD { 0 } , { 1 } '' , x , y ) ; if ( x < y ) return Gcd ( y , x ) ; if ( x % y == 0 ) return y ; return Gcd ( y , x % y ) ; } static void Main ( string [ ] args ) { Big... | C # 64 bit release build started without debugging behaves differently to when started with debugging ( BigInteger ) |
C# | I noticed something strange and there is a possibility I am wrong.I have an interface IA and class A : In other class I have this : But I get compilation error.But if I change it to : Everything is fine.Why is it ? | interface IA { ... . } class A : IA { ... . } private IList < A > AList ; public IList < IA > { get { return AList ; } } public IList < IA > { get { return AList.ToArray ( ) ; } } | list.ToArray vs list |
C# | I 've run into this several times , so would like to use a real example and get ideas on how more experienced C # developers handle this.I 'm writing a .NET wrapper around the unmanaged MediaInfo library , which gathers various data about media files ( movies , images ... ) .MediaInfo has many functions , each applying... | General Video Audio Text Image Chapters Menu ( Name of function ) x x x x x x x Formatx x x x x x x Titlex x x x x x x UniqueIDx x x x x x CodecIDx x x x x x CodecID/Hint x x x x x Languagex x x x x Encoded_Datex x x x x Encoded_Libraryx x x x x InternetMediaTypex x x x x StreamSize x x x x BitDepth x x x x Compression... | Class design for system which is hierarchical , but not neatly so |
C# | Our application can share code . For example user is sharing the html code as followswhich is not in a perfect format ... . Now i need to achieve the ( auto ) code formatting ... i.e . after auto code format click , it should look like So , is there ready made plugin available or is there any way ( s ) to achieve it ei... | < div id= '' nav-vert-one '' > < ul > { { for GroupCollection } } < li > < a href= '' # '' title= '' { { : Name } } '' onclick= '' test ( ) '' > { { : Name } } < /a > ( ' { { : GroupId } } ' ) '' > < /li > { { /for } } < /ul > < div id= '' nav-vert-one '' > < ul > { { for GroupCollection } } < li > < a href= '' # '' ti... | How to achieve ( auto ) code format selection of any html code via jQuery / C # ? ( Any solution ) |
C# | I often find I want to write code something like this in C # , but I am uncomfortable with the identifier names : Here we have four different things called `` engine '' : Engine the class . Engine seems like a good , natural name.Engine the public property . Seems silly to call it MyEngine or TheCarsEngine.engine the p... | public class Car { private Engine engine ; public Engine Engine { get { return engine ; } set { engine = value ; } } public Car ( Engine engine ) { this.engine = engine ; } } | How would you name these related Property , Class , Parameter and Field in .NET ? |
C# | I have created an extension function , which takes the string as input and check for the value and based on the Generic Type , cast it to the destination type and return it , it 's working well.Now the problem is if i pass the input value as empty it should return null , for nullable types , but it simply throws except... | String was not recognized as a valid DateTime public static class Extension { public static T ToNull < T > ( this string value ) { var stringType = `` System.Nullable ` 1 [ [ System . { 0 } , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] '' ; if ( typeof ( T ) == typeof ( String ) )... | Returning null for generic type extension in c # |
C# | I 've been reading Tim McCarthy 's awesome book on DDD in .NET . In his example application though , his underlying data access is using SqlCE and he 's handcrafting the SQL inline.I 've been playing with some patterns for leveraging Entity Framework but I 've gotten stuck on how exactly to map the IRepository linq que... | public EFCustomerRepository : IRepository < DomainEntities.Customer > { IEnumerable < DomainEntities.Customer > GetAll ( Expression < Func < DomainEntities.Customer , bool > > predicate ) { //Code to access the EF Datacontext goes here ... } } | Is there a suggested pattern for using LINQ between the Model & DataAccess Layers in a DDD based Layered Architecture |
C# | I have the following class as a DataSource for a ListBox : The problem is , this by default will use the Value just as a regular character added to a string , for example if I define this class for Tab like this : The string representation will be : But I need it to beHow to do this ? ! | class SeparatorChars { /// < summary > /// Text to describe character /// < /summary > public string Text { get ; set ; } /// < summary > /// Char value of the character /// < /summary > public char Value { get ; set ; } /// < summary > /// Represent object as string /// < /summary > /// < returns > String representing... | Representing a Char with equivalent string |
C# | Result : `` Derived : :Foo ( object o ) '' WHY ? ? ? | using System ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { var a = new Derived ( ) ; int x = 123 ; a.Foo ( x ) ; } } public class Base { public virtual void Foo ( int x ) { Console.WriteLine ( `` Base : :Foo '' ) ; } } public class Derived : Base { public override void Foo ( i... | Why this method called ? |
C# | While working on a project I ran into the following piece of code , which raised a performance flag.I decided to run a couple of quick tests comparing the original loop to the following loop : and threw this loop in too to see what happens : I also populated the original list 3 different ways : 50-50 ( so 50 % of value... | foreach ( var sample in List.Where ( x = > ! x.Value.Equals ( `` Not Reviewed '' ) ) ) { //do other work here count++ ; } foreach ( var sample in List ) { if ( ! sample.Value.Equals ( `` Not Reviewed '' ) ) { //do other work here count++ ; } } var tempList = List.Where ( x = > ! x.Value.Equals ( `` Not Reviewed '' ) ) ... | foreach loop List performance difference |
C# | The premise of my question , in plain english : A library named Foo depends on a library named BarA class within Foo extends a class within BarFoo defines properties/methods that simply pass-through to BarAn application , FooBar , depends only on FooConsider the following sample : Foo is defined as followsBar is define... | class Program { static void Main ( string [ ] args ) { Foo foo = Foo.Instance ; int id = foo.Id ; // Compiler is happy foo.DoWorkOnBar ( ) ; // Compiler is not happy } } public class Foo : Bar { public new static Foo Instance { get = > ( Foo ) Bar.Instance ; } public new int Id { get = > Bar.Id ; } public void DoWorkOn... | Why can the C # compiler `` see '' static properties , but not instance methods , of a class in a DLL that is not referenced ? |
C# | I 'm using a list to store a pair of hexadecimal values ( eg . in the list AD38F2D8 , displayed as : Value_A : AD 38 F2 D8 ) .My question is should I use a Dictionary < string , string > or should I use Dictionary < string , NewCustomObject > to store the hexadecimal string as a pair of strings . ( Value : [ AD , 38 , ... | Index = 0 , Value = 3D95FF08Index = 1 , Value = 8D932A08 Index = 0 , Key = First , Value = 3D95FF08Index = 1 , Key = Second , Value = 8D932A08 Index = 0 , Key = First , Value = 3D , 95 , FF , 08Index = 1 , Key = Second , Value = 8D , 93 , 2A , 08 BYTE 0 1 2 3 to 6 ... ..HEX AD 12 01 0000859D ... .. Index Reference Link... | C # dictionary or just keep using lists ? |
C# | I have an extension for ActionResult that adds a toast to TempData when returning a page : and this is InformMessageResult : This works well with and the like , but fails withand the debugger highlightssaying InnerResult not set to an instance of an object.Is there a way I can make this work with Return Page ( ) ? Edit... | public static IActionResult WithMessage ( this ActionResult result , InformMessage msg ) { return new InformMessageResult ( result , msg ) ; } public class InformMessageResult : ActionResult { public ActionResult InnerResult { get ; set ; } public InformMessage InformMessage { get ; set ; } public InformMessageResult (... | ActionResult extension does n't work with Page ( ) ActionResult method |
C# | Let 's say we have this class : If I add an object of this type to a Hashtable , then I can find the object using the identical string.But if the Hashtable contains the string not the object , it fails to find it when I pass the object.I 've tried overriding operator== and it made no difference.Is it possible to use im... | public class Moo { string _value ; public Moo ( string value ) { this._value = value ; } public static implicit operator string ( Moo x ) { return x._value ; } public static implicit operator Moo ( string x ) { return new Moo ( x ) ; } public override bool Equals ( object obj ) { if ( obj is string ) return this._value... | Implicit casting of an object to string , for use in a Hashtable |
C# | I have created a little windows service which should delete all occurrences of a certain file name in certain folders.All this code runs in the elapsed-handler of the timer ( intervall=10s ) .When the service is running I can recognize a CPU increase up to 20 % used by that service , so I examined my code , put some tr... | var files1 = Directory.EnumerateFiles ( dirSwReporter , swReporterFileName , SearchOption.AllDirectories ) ; var files2 = Directory.EnumerateFiles ( dirSwReporter2 , swReporterFileName , SearchOption.AllDirectories ) ; var allReporterFiles = files1.Union ( files2 ) ; var sw = Stopwatch.StartNew ( ) ; var fileCount = al... | Call to IEnumerable.Count ( ) takes multiple seconds |
C# | I want to check if an icon exists in the systray ; as in , if `` X '' application has displayed their systray icon in the systray area.I 've Googled for information about how to do this but I did n't find anything . UPDATE : This what I 've tried in VB.NET translating the C # examples of the url gived by Robert comment... | Imports System.Runtime.InteropServicesPublic Class Form1 Public Declare Function FindWindow Lib `` user32.dll '' Alias `` FindWindowA '' ( ByVal lpClassName As String , ByVal lpWindowName As String ) As Long Public Declare Function FindWindowEx Lib `` user32.dll '' Alias `` FindWindowExA '' ( ByVal hWndParent As IntPtr... | Icon exists in systray ? |
C# | I have an application which saves documents ( think word documents ) in an Xml based format - Currently C # classes generated from xsd files are used for reading / writing the document format and all was well until recently when I had to make a change the format of the document . My concern is with backwards compatabil... | < doc > < ! -- Existing document -- > < myElement > Hello World ! < /myElement > < /doc > < doc > < ! -- Existing document -- > < someElement contents= '' 12 '' / > < /doc > < doc > < ! -- Existing document -- > < someElement > < contents > 12 < /contents > < contents > 13 < /contents > < /someElement > < /doc > | How should I manage different incompatible formts of Xml based documents |
C# | Let 's imagine we have an animation that changes a Rectangle 's width from 50 to 150 when user moves the cursor over it and back from 150 to 50 when user moves the cursor away . Let the duration of each animation be 1 second.Everything is OK if user moves the cursor over the rectangle , then waits for 1 second for anim... | < Rectangle Width= '' 50 '' Height= '' 100 '' HorizontalAlignment= '' Left '' Fill= '' Black '' > < Rectangle.Triggers > < EventTrigger RoutedEvent= '' MouseEnter '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Storyboard.TargetProperty= '' Width '' To= '' 150 '' Duration= '' 0:0:1 '' / > < /Storyboard > < /B... | How to make the duration of an animation dynamic ? |
C# | I follow the naming convention of MethodName_Condition_ExpectedBehaviourwhen it comes to naming my unit-tests that test specific methods.for example : But when I need to rename the method under test , tools like ReSharper does not offer me to rename those tests.Is there a way to prevent such cases to appear after renam... | [ TestMethod ] public void GetCity_TakesParidId_ReturnsParis ( ) { ... } | Is there a way to protect Unit test names that follows MethodName_Condition_ExpectedBehaviour pattern against refactoring ? |
C# | Does an IEnumerable have to use Yield to be deferred ? Here is test code which has helped me understand deferred execution and yield . | //immediate execution public IEnumerable Power ( int number , int howManyToShow ) { var result = new int [ howManyToShow ] ; result [ 0 ] = number ; for ( int i = 1 ; i < howManyToShow ; i++ ) result [ i ] = result [ i - 1 ] * number ; return result ; } //deferred but eager public IEnumerable PowerYieldEager ( int numb... | Does an IEnumerable have to use Yield to be deferred |
C# | I read this article about Task.ConfigureAwait which can help to prevent deadlocks in async code.Looking at this code : ( I know I should n't do .Result , But it 's a part of the question ) This will result a deadlock because : The .Result - operation will then block the current thread ( i.e the UI thread ) while it wai... | private void Button_Click ( object sender , RoutedEventArgs e ) { string result = GetPageStatus ( ) .Result ; Textbox.Text = result ; } public async Task < string > GetPageStatus ( ) { using ( var httpClient = new HttpClient ( ) ) { var response = await httpClient.GetAsync ( `` http : //www.google.com '' ) ; return res... | await and deadlock prevention - clarification ? |
C# | this code that adds registers new EventHandler ( s ) for an event named as NewMail ( the eventargs class is named NewMailEventArgs . ( source : CLR via C # , chapter 11 Events ) What I do n't understand is the do part , first we are assigning newMail to prevHandler , then newMail is changed ( in CompareExchange ) to ne... | // A PUBLIC add_xxx method ( xxx is the event name ) // Allows methods to register interest in the event.public void add_NewMail ( EventHandler < NewMailEventArgs > value ) { // The loop and the call to CompareExchange is all just a fancy way // of adding a delegate to the event in a thread-safe way . EventHandler < Ne... | EventHandler : What is going on in this code ? |
C# | I am creating a AppDomain using the below codeBut _Domain.DynamicDirectory property does not exist . https : //msdn.microsoft.com/en-us/library/system.appdomain.dynamicdirectory ( v=vs.110 ) .aspx clearly says the AppDomainSetup.DynamicBase is used . What could be the reason executing in vstest.console.exe changes the ... | String pa = @ '' C : \Users\user\AppData\Local\Temp\2\db5fjamk.xnl '' ; System.IO.Directory.CreateDirectory ( pa ) ; AppDomainSetup setup = new AppDomainSetup ( ) ; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory ; //f : \projectpath\out\debug-i386-unittest\UnitTestssetup.ApplicationName = string.Concat (... | AppDomain.DynamicDirectory is not generated |
C# | Just thought I 'd see if somebody could explain why Anders decided that this is valid ... but this is not ... | if ( ... ) //single statementelse ///single statement try //single statementcatch //single statement | Single statement conditionals - why is the pattern not used for other code blocks ? |
C# | I have a legacy map viewer application using WinForms . It is sloooooow . ( The speed used to be acceptable , but Google Maps , Google Earth came along and users got spoiled . Now I am permitted to make if faster : ) After doing all the obvious speed improvements ( caching , parallel execution , not drawing what does n... | public Point MapToScreen ( PointF input ) { // Note that North is negative ! var result = new Point ( ( int ) ( ( input.X - this.currentView.X ) * this.Scale ) , ( int ) ( ( input.Y - this.currentView.Y ) * this.Scale ) ) ; return result ; } public struct Position { public const int PrecisionCompensationPower = 20 ; pu... | Offloading coordinate transformations to GPU |
C# | According to the MSDN : Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties , two instances of the same anonymous type are equal only if all their properties are equal.However , the following code demonstrates the compiler generated implemen... | DateTime start = new DateTime ( 2009,1,1 ) ; DateTime end = new DateTime ( 2010 , 12,31 ) ; // months since year 0 int startMonth = start.Date.Year * 12 + start.Date.Month - 1 ; int endMonth = end.Date.Year * 12 + end.Date.Month -1 ; // iterate through month-year pairs for ( int i = startMonth ; i < = endMonth ; i++ ) ... | `` == '' Operator Does n't Behave Like Compiler-generated Equals ( ) override for anonymous type |
C# | I am making a ListView inside my C # file . But instead of that I want to add the data I get from sqlite too the xaml file with data binding so I can still edit the layout with xaml . So every response from sqlite needs to be added as label ( < TextCell Text= '' { Binding Name } '' / > ) .My question : How can I bind t... | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ContentPage xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' x : Class= '' AmsterdamTheMapV3.CategoriePage '' > < ListView x : Name= '' listView '' > < ListView.ItemTemplate > < DataTemplate > < Te... | how can I bind a full response from SQLite ? |
C# | Here is some sample code I have basically written thousands of times in my life : And it seems to me C # should already have something that does this in just a line . Something like : But that does n't return the thing ( or an index to the thing , which would be fine ) , that returns the goodness-of-fit value.So maybe ... | // find bestest thingyThing bestThing ; float bestGoodness = FLOAT_MIN ; foreach ( Thing x in arrayOfThings ) { float goodness = somefunction ( x.property , localvariable ) ; if ( goodness > bestGoodness ) { bestGoodness = goodness ; bestThing = x ; } } return bestThing ; return arrayOfThings.Max ( delegate ( x ) { ret... | Return best fit item from collection in C # 3.5 in just a line or two |
C# | Is there a way to change C # object values all at once ... in one line ? So if I have a class Result with string msg and bool isPositive and I already call the constructor somewhere before like var result = new Result ( ) ; can I change values somehow by not entering : But doing something like what you can do while ins... | result.msg = `` xxxxxx '' ; result.bool = false ; result { msg = `` '' , bool = true } var result = new Result ( ) { msg = `` '' , bool = true } | C # initialized object values |
C# | I have 1 Table in Oracle SQL Developer which containts 1 column as Float.Data reader have should return Decimal for oracle float datatype as per the table given here : https : //docs.microsoft.com/en-us/dotnet/framework/data/adonet/oracle-data-type-mappingsBut the problem is datareader returns double as datatype for Fl... | static void Test ( ) { using ( OracleConnection connection = new OracleConnection ( `` connection string '' ) { connection.Open ( ) ; using ( OracleCommand command = connection.CreateCommand ( ) ) { command.CommandText = `` select id , NFLOAT from Numeric_Table '' ; using ( OracleDataReader reader = command.ExecuteRead... | DataReader returning incorrect .net datatype for database table float column |
C# | Good day , I need to make function that will iterate on Dictionary that stores variable name and variable ` s new value . After that , I need to update class variable with that value.It works but I want little improvement and I absolutely do n't know if it is possible . As you can see , that function can accept any cla... | void UpdateValues ( Type type , Dictionary < string , string > values ) { foreach ( var value in values ) { var fieldInfo = selected.GetComponent ( type ) .GetType ( ) .GetField ( value.Key ) ; if ( fieldInfo == null ) continue ; fieldInfo.SetValue ( selected.GetComponent ( type ) , value.Value ) ; } } class test { pub... | FieldInfo update subfield of field |
C# | I encountered a behavior in VB.NET today regarding boxing and reference comparison that I did not expect . To illustrate I wrote a simple program which tries to atomically update a variable of any type.Here is a program in C # ( https : //dotnetfiddle.net/VsMBrg ) : The output of this program is : This is as expected a... | using System ; public static class Program { private static object o3 ; public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; Test < DateTimeOffset ? > value = new Test < DateTimeOffset ? > ( ) ; Console.WriteLine ( value.Value == null ) ; DateTimeOffset dt1 = new DateTimeOffset ( 2017 , 1 , 1 , 1 , 1... | Difference in object boxing / comparing references between C # and VB.Net |
C# | As per this msdn documentationIf the current instance is a reference type , the Equals ( Object ) method tests for reference equality , and a call to the Equals ( Object ) method is equivalent to a call to the ReferenceEquals method.then why does following code results in two different result of method calls Equals met... | using System ; public class Program { public static void Main ( ) { var obj = new { a = 1 , b = 1 } ; var obj1 = new { a = 1 , b = 1 } ; Console.WriteLine ( `` obj.IsClass : `` + obj.GetType ( ) .IsClass ) ; Console.WriteLine ( `` object.ReferenceEquals ( obj , obj1 ) : `` + object.ReferenceEquals ( obj , obj1 ) ) ; Co... | Why do the results of the Equals and ReferenceEquals methods differ even though variables are reference types ? |
C# | I 'm trying to create a small code generator using Roslyn or as it is called now .NET Compiler Platform , prevously I worked with codedom , which was cumbersome but MSDN got a reference , now Roslyn has little documentation and all documentation is focused on code analysis instead of code generation.So my question is s... | private const string MyString = `` This is my string '' ; | Howto create a const declaration using .NET Compiler Platform |
C# | Is there any difference between accessing a property that has a backing fieldversus an auto-property ? The reason I 'm asking is that when letting ReSharper convert a property into an auto property it seems to scan my entire solution , or at least all aspx-files . I ca n't see any reason why there should be any differe... | private int _id ; public int Id { get { return _id ; } set { _id = value ; } } public int Id { get ; set ; } | Why does ReSharper need to scan all files when converting a property to an auto property ? |
C# | there are several threads on value-ranges in enums ( not possible ) .But I have the following problem and search the best solution , where none of the provided once really satisfied me.A specification of a protocol says that byte [ x ] of a message , the messagetype , has the following possible values ( fantasy values ... | 0x00 = get0x01 = set 0x02 to 0xFF = identify class MessageType { public enum MessageTypeEnum { get = 0x00 , set = 0x01 , identify = 0x02 } public static MessageTypeEnum getLogicalValue ( byte numericalValue ) { if ( numericalValue < 0x02 ) return ( MessageTypeEnum ( numericalValue ) ) ; else return MessageTypeEnum.iden... | C # alternative to enums for a n : m-relation |
C# | Ok , so I 'm a bit confused as to what is going on with the following data.We have the following Structure in our application : Portal.Web - An MVC 3 Web App which basically contains all theviews , scripts , css and HTML helper extension methodsPortal.Core - A Class Library which is basically our Business Objects , we ... | var client = new Client ( ) ; | Can MVC Views access all projects even though they are n't referenced by the project where the views are ? |
C# | I 'm trying to set the image on a TableCell.This is my code : This works perfect while testing on an emulator , but when I try to debug this on my iPhone 5 , I get this error : The error happens on the line where I load the image : | public override UITableViewCell GetCell ( UITableView tableView , MonoTouch.Foundation.NSIndexPath indexPath ) { UITableViewCell cell = tableView.DequeueReusableCell ( cellIdentifier ) ; Parking parking = ( tableItems.ToArray ( ) [ indexPath.Row ] as Parking ) ; if ( cell == null ) { cell = new UITableViewCell ( UITabl... | Error on loading image when testing on iPhone 5 |
C# | I always thought base.Something was equivalent to ( ( Parent ) this ) .Something , but apparently that 's not the case . I thought that overriding methods eliminated the possibility of the original virtual method being called.Why is the third output different ? | void Main ( ) { Child child = new Child ( ) ; child.Method ( ) ; //output `` Child here ! '' ( ( Parent ) child ) .Method ( ) ; //output `` Child here ! '' child.BaseMethod ( ) ; //output `` Parent here ! `` } class Parent { public virtual void Method ( ) { Console.WriteLine ( `` Parent here ! `` ) ; } } class Child : ... | Virtual base members not seeing overrides ? |
C# | I have read in Jon 's Skeet online page about how to create a thread safe Singleton in C # http : //csharpindepth.com/Articles/General/Singleton.aspxin the paragraph below this code it says : As hinted at before , the above is not thread-safe . Two different threads could both have evaluated the test if ( instance==nul... | // Bad code ! Do not use ! public sealed class Singleton { private static Singleton instance=null ; private Singleton ( ) { } public static Singleton Instance { get { if ( instance==null ) { instance = new Singleton ( ) ; } return instance ; } } } | Thread safe Singleton : why the memory model does not guarantee that the new instance will be seen by other threads ? |
C# | Given a generic type T in C # , I wonder how to acquire type Q , which is equal to T ? for non-nullable T , and T for already nullable T.The question arose from real code . I want to unify access to parameters passed through query string in my ASP.NET application . And I want to specify a default value of the same type... | public static T FetchValue < T > ( string name , < T ? for non-nullable , T otherwise > default_value = null ) // How to write this ? { var page = HttpContext.Current.Handler as Page ; string str = page.Request.QueryString [ name ] ; if ( str == null ) { if ( default_value == null ) { throw new HttpRequestValidationExc... | `` Promote '' generic type to Nullable in C # ? |
C# | When button1 is clicked , the below code is executed which will run a PowerShell script to get the current SQL Server Instances . However when this is run , the result set ( results variable ) has a count of 0 rows from the PowerShell output . When I run the same code in native PowerShell it displays 3 rows with the in... | private void button1_Click ( object sender , EventArgs e ) { //If the logPath exists , delete the file string logPath = `` Output.Log '' ; if ( File.Exists ( logPath ) ) { File.Delete ( logPath ) ; } string [ ] Servers = richTextBox1.Text.Split ( '\n ' ) ; //Pass each server name from the listview to the 'Server ' vari... | Powershell resultset not being picked up in C # |
C# | I am trying to build a simple leave request application in windows workflow foundation 4.5 , it throws the following exception as the workflow tries to complete without waiting for approveRequest activity . Two SendParameters objects with same ServiceContractName and OperationName 'ApplyLeave ' have different parameter... | using System ; using System.ServiceModel.Activities ; using System.Activities ; using System.ServiceModel ; using System.Activities.Statements ; namespace DemoWF { public class _25_LeaveRequest { public WorkflowService GetInstance ( ) { WorkflowService service ; Variable < int > empID = new Variable < int > { Name = ``... | Human based task in windows workflow foundation |
C# | I have a stylesheet in my application ~/Content/theme/style.css . It is referenced in my application using standard bundling as such : Now , I have used a Sass compiler ( Libsass ) to allow me to change the output style.css file to a customised user output file as required.So basically I do something like this.and then... | bundles.Add ( new StyleBundle ( `` ~/Content/css '' ) .Include ( `` ~/Content/font-awesome/font-awesome.css '' , `` ~/Content/theme/style.css '' ) ) ; CompilationResult compileResult = SassCompiler.CompileFile ( Server.MapPath ( Path.Combine ( WebConfigSettings.RootSassPath , `` style.scss '' ) , options : new Compilat... | Overwriting ASP.NET MVC active stylesheet bundle |
C# | I am annoyed because I would like to call a generic method from a another generic method..Here is my code : So in fact when I call ToList who is an extension to DataTable class ( learned Here ) The compiler says that Y is not a non-abstract Type and he ca n't use it for .ToList < > generic method..What am I doing wrong... | public List < Y > GetList < Y > ( string aTableName , bool aWithNoChoice ) { this.TableName = aTableName ; this.WithNoChoice = aWithNoChoice ; DataTable dt = ReturnResults.ReturnDataTable ( `` spp_GetSpecificParametersList '' , this ) ; //extension de la classe datatable List < Y > resultList = ( List < Y > ) dt.ToList... | Call a generic method with a generic method |
C# | I often work with classes that represent entities produced from a factory . To enable easy testing of my factories easily I usually implement IEquatable < T > , whilst also overriding GetHashCode and Equals ( as suggested by the MSDN ) .For example ; take the following entity class which is simplified for example purpo... | public class Product : IEquatable < Product > { public string Name { get ; private set ; } public Product ( string name ) { Name = name ; } public override bool Equals ( object obj ) { if ( obj == null ) { return false ; } Product product = obj as Product ; if ( product == null ) { return false ; } else { return Equals... | Should I be using IEquatable to ease testing of factories ? |
C# | I have a task to create program that 'll match digits without numbers infront of them . For example : 6x^2+6x+6-57+8-9-90xI 'm trying to use Regex to capture all numbers with + or - before them - but without x afterwards . I 've tried but it seems to capture the '-90 ' from '-90x ' as well . | \ [ +- ] ( \d+ ) [ ^x ] | Regex - Capture only numbers that do n't have a letter next to them |
C# | I ran the following console application : in order to compare the time we need to iterate through the elements of a collection and if it was better to build this collection using a List or an IEnumerable . To my surprise , the result it was 00:00:00.0005504 for the List and 00:00:00.0016900 for the IEnumerable . I was ... | class Program { static void Main ( string [ ] args ) { int n = 10000 ; Stopwatch s = new Stopwatch ( ) ; s.Start ( ) ; List < int > numbers = GetListNumber ( n ) ; foreach ( var number in numbers ) { } s.Stop ( ) ; Console.WriteLine ( s.Elapsed ) ; Console.WriteLine ( ) ; s.Restart ( ) ; foreach ( var number in GetEnum... | List < T > vs IEnumerable < T > |
C# | Is it possible to execute code quick test in VS2010 ? For example I would like to test code below just selecting it in code editor and execute it by passing variables ? | public static int GetInt ( object value ) { int result ; Int32.TryParse ( GetString ( value ) , out result ) ; return result ; } | Quick test code option in VS2010 |
C# | I 'm doing a code review and found a line where one of our developers is creating an object using an empty object initializer like this : I do n't know why he would instantiate this way rather than : Are there any downsides to object instantiation using empty object initializers ? Other than being stylistically inconsi... | List < Floorplan > floorplans = new List < Floorplan > { } ; List < Floorplan > floorplans = new List < Floorplan > ( ) ; | Are there any downsides to using an empty object initializer ? |
C# | Here is my code : I got a process by its id . That worked fineThen I tried to send something to its stdin . That threw an InvalidOperationException . Note : the exception occured when I tried to get the StandardInput , not when I tried to us WriteLine.I believe I know why I got the exception . The process was not start... | static void Main ( string [ ] args ) { if ( args.Length > 1 ) { int id ; if ( int.TryParse ( args [ 0 ] , out id ) ) { try { var p = Process.GetProcessById ( id ) ; p.StandardInput.WriteLine ( args [ 1 ] ) ; } catch ( ArgumentException ) { Console.WriteLine ( $ '' Could n't find process with id { id } '' ) ; } } else {... | Writeline to already running process |
C# | In C # 5 , the closure semantics of the foreach statement ( when the iteration variable is `` captured '' or `` closed over '' by anonymous functions ) was famously changed ( link to thread on that topic ) .Question : Was it the intention to change this for arrays of pointer types also ? The reason why I ask is that th... | foreach ( V v in x ) EMBEDDED-STATEMENT { T [ , ,… , ] a = x ; V v ; for ( int i0 = a.GetLowerBound ( 0 ) ; i0 < = a.GetUpperBound ( 0 ) ; i0++ ) for ( int i1 = a.GetLowerBound ( 1 ) ; i1 < = a.GetUpperBound ( 1 ) ; i1++ ) … for ( int in = a.GetLowerBound ( N ) ; iN < = a.GetUpperBound ( n ) ; iN++ ) { v = ( V ) a.GetV... | Closure semantics for foreach over arrays of pointer types |
C# | On www.dofactory.com I found a real world example of the Factory Pattern . But the code generates a warning in ReSharper about a virtual member call in the constructor.The code causing the warning is the following : In the consuming code , you can then simply use : I do understand why it 's a bad idea to call a virtual... | abstract class Document { private List < Page > _pages = new List < Page > ( ) ; // Constructor calls abstract Factory method public Document ( ) { this.CreatePages ( ) ; // < = this line is causing the warning } public List < Page > Pages { get { return _pages ; } } // Factory Method public abstract void CreatePages (... | How to prevent Factory Method pattern causing warning about virtual member call in constructor ? |
C# | I have a small app with several forms , each of which saves their pane layout during the FormClosing event.Some forms need to remain on screen when the main form is minimized , so they 're opened ownerless with form.Show ( ) , as opposed to form.Show ( this ) .However this affects FormClosing behaviour - when the user ... | public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; this.Text = `` Main '' ; Form ownedForm = new Form { Text = `` Owned '' } ; ownedForm.FormClosing += ( s , e ) = > { System.Diagnostics.Debug.WriteLine ( `` FormClosing owned form '' ) ; } ; ownedForm.Show ( this ) ; Form ownerlessForm = n... | How to fire FormClosing for ownerless forms on red X exit ? |
C# | I have the following method that I ca n't figure out correct syntax to call : I 'm trying to call it like this : Edited : thx everyone , you guys helped turned on a light bulb in my head . here is what i did : not sure why i even an issue with this . it 's one of those days i guess..thx | public T GetAndProcessDependants < C > ( Func < object > aquire , Action < IEnumerable < C > , Func < C , object > > dependencyAction ) { } var obj = MyClass.GetAndProcessDependants < int > ( ( ) = > DateTime.Now , ( ( ) = > someList , ( id ) = > { return DoSomething ( x ) ; } ) } var obj = MyClass.GetAndProcessDependa... | C # Action < > with Func < > parameter |
C# | I have a winforms TabControl and I am trying to cycle through all the controls contained in each tab . Is there a way to add and in a foreach loop or is n't it possible to evaluate more than one group of items ? For example this is what I 'd like to do : ORIs this possible , and if not , what is the next best thing ? D... | foreach ( Control c in tb_Invoices.Controls and tb_Statements.Controls ) { //do something } foreach ( Control c in tb_Invoices.Controls , tb_Statements.Controls ) { //do something } | Can I evaluate two groups of items with a foreach loop in C # winforms ? |
C# | Let 's take the following code : This will compile , and all is good . However , let 's now remove the this . prefix : In this case , I get a compiler error . I agree this is an error , however it 's the location of the error that confuses me . The error happens on the line : With the message : A local variable named '... | class Foo { string bar ; public void Method ( ) { if ( ! String.IsNullOrEmpty ( this.bar ) ) { string bar = `` Hello '' ; Console.Write ( bar ) ; } } } class Foo { string bar ; public void Method ( ) { if ( ! String.IsNullOrEmpty ( bar ) ) // < -- Removed `` this . '' { string bar = `` Hello '' ; Console.Write ( bar ) ... | Weird C # compiler issue with variable name ambiguity |
C# | Right now , I am using the following code to create a Shuffle extension : I am looking for a way more faster and efficient way to do this . Right now , using the Stopwatch class , it is taking about 20 seconds to shuffle 100,000,000 items . Does anyone have any ideas to make this faster ? | public static class SiteItemExtensions { public static void Shuffle < T > ( this IList < T > list ) { var rng = new Random ( ) ; int n = list.Count ; while ( n > 1 ) { n -- ; int k = rng.Next ( n + 1 ) ; T value = list [ k ] ; list [ k ] = list [ n ] ; list [ n ] = value ; } } } | Improving `` shuffle '' efficiency |
C# | I create 2 methods that print x and y 100 times . I want them to run concurrent and I expect the output to be xxxxyxyxyyyxyyxyx ... sthg like that.It does n't print anything . Am I missing some logic here ? | using System ; using System.Threading.Tasks ; namespace ConsoleApplication32 { internal class Program { public static async Task < int > Print1 ( ) { await Task.Run ( ( ) = > { for ( int i = 0 ; i < 100 ; i++ ) { Console.Write ( `` x '' ) ; } } ) ; return 1 ; } public static async Task < int > Print2 ( ) { await Task.R... | Why nothing is printed on the console ? |
C# | I just found that not only does this code compile , it seems to split the string on any whitespace.However it did n't show in the intellisense and it 's not on the MSDN page . Is this just an undocumented override ? And is it dangerous to use because of that ? | List < string > TableNames = Tables.Split ( ) .ToList ( ) ; | Is this an undocumented override of the Split method ? |
C# | Is there any way in a C # iterator block to provide a block of code which will be run when the foreach ends ( either naturally of by being broken out of ) , say to clean up resources ? The best I have come up with is to use the using construct , which is fine but does need an IDisposable class to do the clean up . For ... | public static IEnumerable < string > ReadLines ( this Stream stream ) { using ( StreamReader rdr = new StreamReader ( stream ) ) { string txt = rdr.ReadLine ( ) ; while ( txt ! = null ) { yield return txt ; txt = rdr.ReadLine ( ) ; } rdr.Close ( ) ; } } | 'Finally ' Block in Iterators |
C# | In Australia , A client has been entering `` 1/5 '' as a shortcut for the first day of May . We have just moved from Windows Server 2008 to Windows Server 2012.Using the following code in LinqPad : On Windows Server 2008 : dd MMMM1/05/2016 12:00:00 AMOn Windows Server 2012 R2 : MMMM d5/01/2016 12:00:00 AMQuestions : Wh... | Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo ( `` en-au '' , false ) ; System.Globalization.DateTimeFormatInfo.CurrentInfo.MonthDayPattern.Dump ( ) ; DateTime.Parse ( `` 1/5 '' ) .Dump ( ) ; | DateTimeFormatInfo.MonthDayPattern Has Changed in Windows Server 2012 - How Can I set it back ? |
C# | Is there a way to find out all function calls that will execute as part of a Program in C # world ? For example , given this : Can I say through FxCop or some other system get to know CallTrueFunction ? | static void Main ( string [ ] args ) { if ( true ) { CallTrueFunction ( ) ; } else { CallFalseFunction ( ) ; } } | .NET Static Analysis -- Guaranteed calls to functions in a program |
C# | Why does the following code produce an error ? Error : Operator ' < ' can not be applied to operands of type 'method group ' and 'System.Type'The code looks silly , because it 's extremly simplified from my real example . I just wonder why it does not work exactly . It works if I replace x.getType ( ) with List < strin... | var listOfList = new List < List < string > > ( ) ; var tmp = listOfList.Select ( x = > x.OrderBy ( y = > y ) .Cast < x.GetType ( ) > ( ) ) ; | Why does Select ( x = > ... Cast < x.GetType ( ) > ( ) ) not work ? |
C# | Consider the following function : This function returns whether it was able to `` do stuff '' on destination based on input 's content.I 'd like to check if the memory regions `` wrapped '' by input and destination intersect , and if so , throw an exception , since this would corrupt input 's data . How can I do that (... | public static bool TryToDoStuff ( ReadOnlySpan < byte > input , Span < byte > destination ) { ... } // On arraysSpan < byte > firstArray = new byte [ 10 ] ; Span < byte > secondArray = new byte [ 10 ] ; Intersects < byte > ( firstArray.Slice ( 5 , 5 ) , firstArray.Slice ( 3 , 5 ) ) ; // Should throwIntersects < byte > ... | How can I check if two Span < T > intersect ? |
C# | the following code sets the clipboard text on OSX . What is the equivalent to read the clipboard text ? | static class OsxClipboard { public static void SetText ( string text ) { var nsString = objc_getClass ( `` NSString '' ) ; var str = objc_msgSend ( objc_msgSend ( nsString , sel_registerName ( `` alloc '' ) ) , sel_registerName ( `` initWithUTF8String : '' ) , text ) ; var dataType = objc_msgSend ( objc_msgSend ( nsStr... | How to get the clipboard text on OSX using DllImport with c # ? |
C# | I have this function I 'm creating 2 Persons class instances : I 'm calling the function with : my Question is : Who actually decide about the T1 type ? ( p ? p2 ? ) Because if the left one is Apple so he checks that the second one is Also an appleand if the second one is Orange - he should check that the first one is ... | public static T2 MyFunc < T1 , T2 > ( T1 a , T1 b , T2 c ) { return c ; } class Person { } Person p = new Person ( ) ; Person p2 = new Person ( ) ; MyClass.MyFunc ( p , p2 , 5 ) ; | Who actually last decide what is the Generic Type ? |
C# | Background : I have a `` Messenger '' class . It sends messages . But due to limitations , let 's say it can only send - at most - 5 messages at a time.I have a WPF application which queues messages as needed , and waits for the queued message to be handled before continuing . Due to the asynchronous nature of the appl... | public async Task Frobulate ( ) { Message myMessage = new Message ( x , y , z ) ; await messenger.SendMessage ( myMessage ) ; //Code down here never executes ! } private TaskScheduler _messengerTaskScheduler = new LimitedConcurrencyLevelTaskScheduler ( 5 ) ; private TaskFactory _messengerTaskFactory = new TaskFactory (... | 'await ' does not return , when my Task is started from a custom TaskScheduler |
C# | I am working on a role playing game for fun and to practice design patterns . I would like players to be able to transform themselves into different animals . For example , a Druid might be able to shape shift into a cheetah . Right now I 'm planning on using the decorator pattern to do this but my question is - how do... | class Druid : Character { // many cool druid skills and spells void LightHeal ( Character target ) { } } abstract class CharacterDecorator : Character { Character DecoratedCharacter ; } class CheetahForm : CharacterDecorator { Character DecoratedCharacter ; public CheetahForm ( Character decoratedCharacter ) { Decorate... | Design considerations for temporarily transforming a player into an animal in a role playing game |
C# | I have data stored in an XML document that describes a linked list ; all nodes except one follow another , so the data looks something like this : ... to give an ordering of 30 , 29 , 34 , 9 , 20 , 12 . I 'm using .NET 's LinkedList class to construct a linked list to reflect this data , but it 's awkward to construct ... | < cars > < car id= '' 9 '' follows= '' 34 '' / > < car id= '' 12 '' follows= '' 20 '' / > < car id= '' 20 '' follows= '' 9 '' / > < car id= '' 29 '' follows= '' 30 '' / > < car id= '' 30 '' / > < car id= '' 34 '' follows= '' 29 '' / > < /cars > LinkedList < CarInstance > orderedCars = new LinkedList < CarInstance > ( )... | Most efficient way to construct a linked list from stored data ? |
C# | It appears that , in .NET , `` array of enum '' is not a strongly-typed concept . MyEnum [ ] is considered to implement not just IEnumerable < MyEnum > , but also IEnumerable < YourEnum > . ( I did n't believe it at first either . ) So when I go looking through a list for everything that implements IEnumerable < T > , ... | // Returns true : typeof ( IEnumerable < DayOfWeek > ) .IsAssignableFrom ( typeof ( AttributeTargets [ ] ) ) // Outputs `` 3 '' : var listOfLists = new List < object > { new [ ] { AttributeTargets.All } , new [ ] { ConsoleColor.Blue } , new [ ] { PlatformID.Xbox , PlatformID.MacOSX } } ; Console.WriteLine ( listOfLists... | Every array of enum implements IEnumerable < EveryOtherEnum > . How do I work around this ? |
C# | Does this make sense ? Having a simple classand then instantiating itThe using statement is there just to make sure Test is disposed.When will it be disposed if I just call | class Test { public Test ( ) { // Do whatever } } using ( new Test ( ) ) { // Nothing in here } new Test ( ) | Using `` using '' statement to dispose |
C# | I am new to programming . I am studying chapter 14 of John Sharp 's Microsoft Visual C # Step by Step 9ed.And I do not understand a number of points.The author writes : ... it ( finalizer ) can run anytime after the last reference to an object has disappeared . So it is possible that the finalizer might actually be inv... | class Example : IDisposable { private Resource scarce ; // scarce resource to manage and dispose private bool disposed = false ; // flag to indicate whether the resource // has already been disposed ... ~Example ( ) { this.Dispose ( false ) ; } public virtual void Dispose ( ) { this.Dispose ( true ) ; GC.SuppressFinali... | C # IDisposable , Dispose ( ) , lock ( this ) |
C# | I 'm working on a sample PRISM application and I want to use the MEF RegistrationBuilder to create all of my exports . The equivalent of using the ExportAttribute is as follows : However , modules use a different attribute , the ModuleExportAttribute , for example : I 'm not sure how to use the RegistrationBuilder clas... | [ Export ( typeof ( IFooService ) ) ] public class FooService : IFooService { ... } Builder.ForTypesMatching ( typeof ( IFooService ) .IsAssignableFrom ( type ) ) .Export < IFooService > ( ) ; [ ModuleExport ( typeof ( ModuleA ) , DependsOnModuleNames = new string [ ] { `` ModuleB '' } ) ] public sealed class ModuleA :... | Is it possible to use MEF RegistrationBuilder to create a PRISM ModuleExport ? |
C# | Is there any downside of calling GC.SuppressFinalize ( object ) multiple times ? Protected Dispose ( bool ) method of the dispose pattern checks whether it is called before but there is no such check in the public Dispose ( ) method.Is it ok to call the Dispose ( ) method of a MyClass instance multiple times ? | public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( _Disposed ) return ; if ( disposing ) { // Cleanup managed resources . } // Cleanup unmanaged resources . _Disposed = true ; } ~MyClass ( ) { Dispose ( false ) ; } | Calling SuppressFinalize multiple times |
C# | Whenever I write a new class and add some internal fields , I use an underscore prefix like so : Why did the .NET team decide to create an AppDomain interface with the name _AppDomain ? It just bugs me to see it whenever I type an underscore to get my class level fields in intellisense . Why is n't it IAppDomain or som... | private readonly int _foo ; | Why is _AppDomain prefixed with an underscore ? Seriously , it bugs me that it is always in my field intellisense |
C# | I have a DataTable which I want to check if values in three of the columns are unique . If not , the last column should be filled with the line number of the first appearance of the value-combination.For example , this table : Should lead to this result : I solved this by iterating the DataTable with two nested for loo... | ID Name LastName Age Flag -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 Bart Simpson 10 -2 Lisa Simpson 8 -3 Bart Simpson 10 -4 Ned Flanders 40 -5 Bart Simpson 10 - Line Name LastName Age Flag -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 Bart Simpson 10 -2 Lisa Simpson 8 -3 Bart Simpson 10 14 Ned... | Mark non-unique rows in a DataTable |
C# | I 'm doing a class that gets a string of a JSON ( that represents an object ) and I 'm deserializing it using JSON.NET from Newtonsoft . As I do n't know exactly the object that I need to serialize what I 'm doing with the JSON.NET library is to get a Dictionary.The thing is that I 'm processing each property different... | { `` firstName '' : '' Mario '' , '' lastName '' : '' Bross '' , '' users '' : [ { `` name '' : '' Tony '' , '' country '' : '' UK '' , '' telephone '' : '' 663242342 '' } , { `` name '' : '' Ahmed '' , '' country '' : '' UAE '' , '' telephone '' : '' 66934534 '' } , { `` name '' : '' Alejandro '' , '' country '' : '' ... | Distinguish byte [ ] and string from JSON .NET |
C# | I want to do something within the FooDataRepository class once the SaveFooAsync and the all the SaveBarAsync methods have completed . Is there a standard pattern for trying to do a single thing based upon N number of Async calls completing ? | public class FooDataRepository { private MyServiceReferenceClient Client { get ; set ; } public void FooClass ( ) { Client = new MyServiceReferenceClient ( ) ; Client.SaveFooCompleted += Client_SaveFooCompleted ; Client.SaveBarCompleted += Client_SaveBarCompleted ; } private void Client_SaveFooCompleted ( Object sender... | Is there a standard pattern to follow when waiting for N number of async methods to complete ? |
C# | I 'm trying to set up automated builds on my build agent using MSBuild on the command line . The two projects I 'm focussed on at the moment are a UWP and it 's associated unit test project.To build , I have to use this : Else , I get this error : However , this does not generate a .cer security certificate . So when I... | /p : AppxPackageSigningEnabled=false error APPX0101 : A signing key is required in order to package this project . Please specify a PackageCertificateKeyFile or PackageCertificateThumbprint value in the project file . error 0x800B0100 : The app package must be digitally signed for signature validation.. | Can vstest.console.exe run an appx without a security certificate |
C# | I am trying to serialize a list of descendants . This is what I have now , that works fine : This works fine and I can serialize both Animals . I wonder If it is possible to create an Attribute class where I can pass the list of animals ( instances ) , and will create for me the XmlArrayItems attributes.In general , I ... | class Animal { } class Zebra : Animal { } class Hippo : Animal { } [ XmlRootAttribute ( `` Zoo '' ) ] class Zoo { [ XmlArrayItem ( typeof ( Zebra ) ) ] [ XmlArrayItem ( typeof ( Hippo ) ) ] public List < Animal > Actions { set ; get ; } } | Xml Serialize List of Descendants |
C# | I have some lines of code in c # that Resharper indents like this : Due to my personal coding style , I would like the above to appear with the closing parenthesis ( or brace ) without any indentation , like so : I tried playing with the various options on Resharper , but could n't find any . Is there a way I can make ... | Console.WriteLine ( `` Hello '' ) ; this.MySuperFunction ( argument1 , argument2 , argument3 ) ; Console.WriteLine ( `` World '' ) ; Console.WriteLine ( `` Hello '' ) ; this.MySuperFunction ( argument1 , argument2 , argument3 ) ; Console.WriteLine ( `` World '' ) ; | Resharper closing parenthesis indentation on function with multiple arguments |
C# | To return a double , do I have to cast to double even if types are double ? e.g.Do I have to cast ( double ) ? | double a = 32.34 ; double b = 234.24 ; double result = a - b + 1/12 + 3/12 ; | To return a double , do I have to cast to double even if types are double in c # ? |
C# | I use VS2015 , C # .I have a problem with Google login . From my debug configuration ( localhost ) everything works fine . After publishing to the server , google login window simply does n't get opened . And no exception is thrown.Here is my code : Of course I added server 's address to the origin uri and also to the ... | [ AllowAnonymous ] public async Task LoginWithGoogle ( ) { HttpRequest request = System.Web.HttpContext.Current.Request ; string redirectUri = ConfigurationReaderHelper.GetGoogleRedirectUri ( ) ; try { ClientSecrets secrets = new ClientSecrets { ClientId = `` *** '' , ClientSecret = `` *** '' } ; IEnumerable < string >... | Google login not working after publish |
C# | I made a simple async method to call an SQL stored procedure asynchronously.In my console program , I am calling this method 1000 times in a loop , and sleep for 1ms ( Thread.Sleep ) between each call.I start a StopWatch before entering the loop , and stop it when exiting the loop , and display the time spent in the lo... | Completed in 1006 ms Completed in 15520 ms public async void CallSpAsync ( ) { var cmd = new SqlCommand ( `` sp_mysp '' ) ; { var conn = new SqlConnection ( connectionString ) ; { cmd.Connection = conn ; cmd.CommandType = CommandType.StoredProcedure ; [ ... Filling command parameters here - nothing interesting ... ] aw... | async method not blocking on desktop but blocking on server ? |
C# | I have an string ; It must return ipad because ipad is in the first match ipad at the string.In other case Same string array first match to iPhone . | String uA = `` Mozilla/5.0 ( iPad ; CPU OS 8_2 like Mac OS X ) AppleWebKit/600.1.4 ( KHTML , like Gecko ) Mobile/12D508 Twitter for iPhone '' ; String [ ] a= { `` iphone '' , '' ipad '' , '' ipod '' } ; String uA = `` Mozilla/5.0 ( iPhone/iPad ; CPU OS 8_2 like Mac OS X ) AppleWebKit/600.1.4 ( KHTML , like Gecko ) Mobi... | How to compare string to String Array in C # ? |
C# | I have the following code : Visual Studio highlights this code , saying 'Possible NullReferenceException'by the way , without await Visual Studio does n't show this warningWhy NullReferenceException is possible here ? | await _user ? .DisposeAsync ( ) ; | await with null propagation System.NullReferenceException |
C# | Using DataTable.Compute , and have built some cases to test : I have changed my code to handle both . But curious to know what 's going on here ? | dt.Compute ( `` 0/0 '' , null ) ; //returns NaN when converted to doubledt.Compute ( `` 0/0.00 '' , null ) ; //results in DivideByZero exception | Why 0/0 is NaN but 0/0.00 is n't |
C# | Recently I have been researching some conventions in writing functions that return a collection . I was wondering whether the function that actually uses a List < int > should return a List < int > or rather IList < int > , ICollection < int > or IEnumerable < int > . I created some tests for performance and I was quit... | static List < int > list = MakeList ( ) ; static IList < int > iList = MakeList ( ) ; static ICollection < int > iCollection = MakeList ( ) ; static IEnumerable < int > iEnumerable = MakeList ( ) ; public static TimeSpan Measure ( Action f ) { var stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; f ( ) ; stopWatch.... | Enumerating List faster than IList , ICollection and IEnumerable |
C# | I have a method called OutputToScreen ( object o ) and it is defined as : In my main calling method , if I do something like : But if I do , I am still not sure why x is not boxed in the second approach , I just saw it on a free video from quickcert . Can someone give good explanation ? Here is an additional question b... | public void OutputToScreen ( object o ) { Console.WriteLine ( o.ToString ( ) ) ; } int x = 42 ; OutputToScreen ( x ) ; // x will be boxed into an object OutputToScreen ( x.ToString ( ) ) ; // x is not boxed | How passing in x.ToString ( ) into a method which is expecting an object type as opposed to just x prevent boxing ? |
C# | Qt has a neat functionality to do timed action with Lambda.An action can be done after a delay with a single line of code : Although I have n't found equivalent in C # .The closest I got was But it 's far from ( visually ) clean . Is there a better way to achieve this ? The use case is sending data on a serial line to ... | QTimer : :singleShot ( 10 , [ = ] ( ) { // do some stuff } ) ; Timer timer = new Timer ( ) ; timer.Interval = 10 ; timer.Elapsed += ( tsender , args ) = > { // do some stuff timer.Stop ( ) ; } ; timer.Start ( ) ; public void DelayTask ( int timeMs , Action lambda ) { System.Timers.Timer timer = new System.Timers.Timer ... | How to delay a C # Action like QTimer : :singleShot ? |
C# | In .NET generic interface ICollection < T > has Count property itself . But it does not inherit any non-generic interface with a Count property . So , now if you want determine count of non-generic IEnumerable , you have to check whether it is implementing ICollection and if not , you have to use reflection to lookup w... | static int ? FastCountOrZero ( this IEnumerable items ) { if ( items == null ) return 0 ; var collection = items as ICollection ; if ( collection ! = null ) return collection.Count ; var source = items as IQueryable ; if ( source ! = null ) return QueryableEx.Count ( source ) ; // TODO process generic ICollection < > -... | Why generic ICollection < T > does not inherit some non-generic interface with Count property ? |
C# | Copy and paste the following into a new console application in VS. Add references to System.Web and System.Web.Services ( I know console apps do n't need these assemblies , I 'm just showing you a snippet of code that does not work in my web application ) .Although both conditions in the if statement are false , it 's ... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Web.Services ; using System.Web ; namespace ConsoleApplication8 { class Program { static void Main ( string [ ] args ) { string x = `` qweqweqw '' ; string y = `` { \ '' textMedia\ '' : [ -1 , -1 , -1 , -1 , -1 ] , \ ... | .net : debugger highlighting line of code not actually being executed |
C# | I find myself constantly wanting to pass a Func with a return and no inputs in place of an Action , for examplewhere , I do n't really care about the return value of DoSomething.These types do n't unify , however , and I end up wrapping the callIs there a way to make these types unify without wrapping ? Also , are ther... | Func < int > DoSomething = ... ; Task.Run ( DoSomething ) ; Task.Run ( ( ) = > { DoSomething ( ) ; } ) ; | Why do n't Func < ... > and Action unify ? |
C# | I 'm looking for suggestions on how to write a query . For each Goal , I want to select the first Task ( sorted by Task.Sequence ) , in addition to any tasks with ShowAlways == true . ( My actual query is more complex , but this query demonstrates the limitations I 'm running into . ) I tried something like this : But ... | var tasks = ( from a in DbContext.Areas from g in a.Goals from t in g.Tasks let nextTaskId = g.Tasks.OrderBy ( tt = > tt.Sequence ) .Select ( tt = > tt.Id ) .DefaultIfEmpty ( -1 ) .FirstOrDefault ( ) where t.ShowAlways || t.Id == nextTaskId select new CalendarTask { // Member assignment } ) .ToList ( ) ; System.Invalid... | Problem with LINQ query : Select first task from each goal |
C# | I found one unpleasant behavior developing with Visual Studio . It was hanging my machine while compiling C # .I have reduced behavior to the next minimal source codeCompiling with ( using Windows 8.1 Pro N x64 ; csc compiler process is running with 32bits ) sightly modifications do n't produce this behavior ( eg . cha... | using System.Collections.Generic ; using System.Linq ; namespace memoryOverflowCsharpCompiler { class SomeType { public decimal x ; } class TypeWrapper : Dictionary < int , Dictionary < int , Dictionary < int , SomeType [ ] [ ] > > > { public decimal minimumX ( ) { return base.Values.Min ( a = > a.Values.Min ( b = > b.... | C # compiler ( csc.exe ) memory overflow compiling nested types and Linq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.