lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | When I start writing a method , I usually check for exceptional conditions first in the method , using If-Then-Throw blocks.This style seems to be very clear and easy to understand , but it takes up more space than I think is necessary . I want to be able to handle errors and exceptional conditions in a smart way that ... | public void ReadFile ( string filePath ) { if ( string.IsNullOrEmpty ( filePath ) { throw new ArgumentException ( ... Assert.IsFalse < ArgumentException > ( string.IsNullOrEmpty ( filePath ) , `` The path can not be null or empty . `` ) ; | Handling the usual errors : If-Then-Throw blocks vs. Code Contracts vs. an Assert class |
C# | I have some problems understanding a way to get the correct result from my LINQ query.Let me first define the entity ProductFavoriteI have an IEnumerable of some favorites products , named allFavorites , containing objects made in the way I wrote before.This `` list '' can contain elements with duplicates ProductUid , ... | public class ProductFavorite { public Guid Uid { get ; set ; } public Guid ProductUid { get ; set ; } public bool IsFavorite { get ; set ; } public bool IsLastUsed { get ; set ; } public int LastUsedYear { get ; set ; } } var favorites = from ProductFavorite pf in allFavorites group pf by pf.ProductUid into distinctFav... | LINQ grouping and aggregating data with conditions |
C# | Let A be a class whith some property Hello . I would like to filter collections of A instances by this property in many places . Thus I 'd make somewhere a static member of type Expression < Func < A , bool > > which denotes the filtering predicate and I use it in all places where I do a filtering . ( This predicate wo... | public static void Main ( ) { var listOfAs = new List < A > ( ) .AsQueryable ( ) ; var query0 = listOfAs .Select ( a = > new WithA < A > { A = a , Smth = a , } ) .Where ( Filter ) ; var listOfBs = new List < B > ( ) .AsQueryable ( ) ; var query1 = listOfBs .Select ( b = > new WithA < B > { A = b.A , Smth = b , } ) .Whe... | How should I share filtering logic between multiple LINQ-where clauses ? |
C# | First of all , sorry for the title , but I could n't think about anything better ... My problem can be presented by simple code sample : Why does Console.WriteLine ( Test < byte > .GetInt ( 20 ) ) ; prints 10 , instead of 30 ? I always thought that generics in .NET are resolved by JIT during runtime . Why then jitter i... | public static class Test < T > { public static int GetInt ( T source ) { return Convert.ToInt32 ( source ) ; } } public static class Convert { public static int ToInt32 ( byte source ) { return 30 ; } public static int ToInt32 ( object source ) { return 10 ; } } | Generics and calling overloaded method from difference class - precedence issue |
C# | I 'm using ReSharpers [ NotNull ] annotations like this : However , due to the NotNull annotation , ReSharper warns me about the unused precondition check , because the expression is always falseBut , as far as I understand those annotations , they only indicate that the parameter should never be null ; i.e . they do n... | public void MyMethod ( [ NotNull ] string a ) { if ( a == null ) // Warning : Expression is always false . { throw new ArgumentNullException ( ) ; } // ... } this.MyMethod ( null ) ; string foo = null ; this.MyMethod ( foo ) ; | Should I add explicit null checks despite ReSharper [ NotNull ] annotations ? |
C# | i was looking for trick to get the form name when mouse is place on it . suppose i have one mdi form and many sdi form like form1 , form2 , form3 and all sdi form are opened . suppose i have one timer running on form1 and which will run periodically . i want to show the form name on form1 's label from the timer tick e... | private void timer1_Tick ( object sender , EventArgs e ) { var handle = WindowFromPoint ( Cursor.Position ) ; if ( handle ! = IntPtr.Zero ) { var ctl = Control.FromHandle ( handle ) ; if ( ctl ! = null ) { label1.Text = ctl.Name ; return ; } } label1.Text = `` None '' ; } [ System.Runtime.InteropServices.DllImport ( ``... | How to detect the form name when mouse is position on any SDI form |
C# | I have a c # console application which has some threads to do some work ( download a file ) .each thread may exit the application at any time any where in application , but I 'll show a proper message on console . It 's possible to track them but it does n't make sense to me . I want simply check thread count or someth... | if ( lastThread ) { cleanUp ( ) ; Console.ReadLine ( ) ; } | Last thread of a multithreaded application |
C# | It was my assumption that the finally block always gets executed as long as the program is running . However , in this console app , the finally block does not seem to get executed.OutputNote : When the exception was thrown , windows askmed me if I wanted to end the appliation , I said 'Yes . ' | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { try { throw new Exception ( ) ; } finally { Console.WriteLine ( `` finally '' ) ; } } } } | Why is n't the finally getting executed ? |
C# | How to check , if a word can be made by letters of another word . using every letter only once.Example : if str = `` computer '' ; then | //if user enters below words output must be true comp put poet//and if user enters below words output must be false count // since n is not in str root // since there is only single o in str | Check if a string can be made by chars of another string in C # |
C# | I have a .NET Core worker application and want to add a custom file logger since Microsoft.Extensions.Logging does not provide this . I do n't want to use an extra package for this ( e.g . Serilog ) .I put information about the log directory and log file into my options class . This options class also has a validator i... | public class MyOptions { public string DirectoryPath { get ; set ; } public string FileName { get ; set ; } } public class MyOptionsValidator : IValidateOptions < MyOptions > { private readonly ILogger < IValidateOptions < MyOptions > > logger ; public MyOptionsValidator ( ILogger < IValidateOptions < MyOptions > > log... | Circular dependency exception when creating a custom logger relying on options with a options validator relying on a logger |
C# | I 'm hoping someone can identify the language feature ( or bug ) that resulted in the change in behaviour of the program below . It is reproduced from a much larger scenario that was intended to log a message if the delegate supplied to Orchard : :Go was not static.The scenario is : If I compile and run a debug build p... | using System ; namespace Sample { public static class Program { public static void Main ( ) { new Apple ( ) ; } } public sealed class Apple { public Apple ( ) { Orchard.Go ( ( ) = > { } ) ; } } internal static class Orchard { public static void Go ( Action action ) { Console.WriteLine ( action.Method.IsStatic ) ; } } }... | Anonymous method staticness different between 2013 and 2015 debug compilations |
C# | I have run into a problem that I 'm not sure how to resolve . I have a method that contains a call from a service that populates a data table such as : So , as you can see , there is n't a way for me to grab just a few cases at a time - it just grabs it all . Right now , I have this method being called in a BackgroundW... | private void GetCases ( ) { try { //Setup our criteria Web_search_criteria myCriteria = new Web_search_criteria ( ) { Keynum = 9 , //Use Opening Date Key Range_start = `` 20100101 '' , //01-01-2010 Range_end = `` 20121223 '' //12-23-2013 } ; //The myCases object is a datatable that is populated from the GetCasesDT ( ) ... | What 's the best way to cancel a long operation ? |
C# | Why can I do this : but not this : It complains that I have n't restricted the generic type enough , but then I would think that rule would apply to casting with `` ( T ) '' as well . | public T GetMainContentItem < T > ( string moduleKey , string itemKey ) { return ( T ) GetMainContentItem ( moduleKey , itemKey ) ; } public T GetMainContentItem < T > ( string moduleKey , string itemKey ) { return GetMainContentItem ( moduleKey , itemKey ) as T ; } | Why does `` as T '' get an error but casting with ( T ) not get an error ? |
C# | i need some help on one line with translating this code : Original in C # : My translation to VB : I get error in line : Error : Value of type Boolean can not be converted to WindowsApplication1.Map_Control.Modal.MapModalTo clarify what am I doing . I am trying to build wpf application and use bing maps . I am followin... | using System.Collections.ObjectModel ; using Microsoft.Maps.MapControl ; namespace Binding_Bing_Map_Control.Modal { public class MapModal { public Location MapLocation { get ; set ; } public string TooltipText { get ; set ; } public static ObservableCollection < MapModal > getMapRecords ( ) { ObservableCollection < Map... | How to translate this line of code from C # to Visual Baisc |
C# | For this piece of code : I 'm geting 'Ol ? ' instead of 'Olá'What 's wrong with it ? | String content = String.Empty ; ListenerStateObject state = ( ListenerStateObject ) ar.AsyncState ; Socket handler = state.workSocket ; int bytesRead = handler.EndReceive ( ar ) ; if ( bytesRead > 0 ) { state.sb.Append ( Encoding.UTF8.GetString ( state.buffer , 0 , bytesRead ) ) ; content = state.sb.ToString ( ) ; ... | Character encoding |
C# | I have been working on a small mathematical scripting engine ( or DSL , if you prefer ) . Making it for fun , its nothing serious . In any case , one of the features I want is the ability to get results from it in a type safe manner . The problem is that there are 5 different types that it can return.Number , bool , Fu... | engine.Eval ( src ) .Match ( ) .Case ( ( Number result ) = > Console.WriteLine ( `` I am a number '' ) ) .Case ( ( bool result ) = > Console.WriteLine ( `` I am a bool '' ) ) .Case ( ( Fun result ) = > Console.WriteLine ( `` I am a function with one argument '' ) ) .Case ( ( AnyFun result ) = > Console.WriteLine ( `` I... | Type safe way to return values from a scripting language in C # |
C# | So I was looking through the implementation of SortedList < TKey , TValue > and the implementation of Add ( which calls Insert shown below ) really surprised me.The Add method does the obvious binary search to determine the index in which the KVP should go , but the Insert seems as if it could be improved significantly... | private void Insert ( int index , TKey key , TValue value ) { if ( this._size == this.keys.Length ) this.EnsureCapacity ( this._size + 1 ) ; if ( index < this._size ) { Array.Copy ( ( Array ) this.keys , index , ( Array ) this.keys , index + 1 , this._size - index ) ; Array.Copy ( ( Array ) this.values , index , ( Arra... | Why SortedList < TKey , TValue > does n't use pointers for the values ? |
C# | If I have the methodI can successfully call it like this : As I imagine the compiler/runtime can infer the type , However If I change the method to this : Then I must call it in 'full ' , specifying both the input parameter type and the return type : Is there a way I can shorthand this so I dont need to specify the inp... | void foo < T > ( T bar ) { } string s = string.Empty ; foo ( s ) ; T foo < T , T2 > ( T2 bar ) { ... } string s = string.Empty ; foo < int , string > ( s ) ; foo < int > ( s ) ; | Shorthand when calling generic methods in c # |
C# | First of all , basically I believe I just need help in figuring out how to calculate it , math isnt really my strong side.FYI , the MS-Word is most likely not relevant to solve my problem , I basically just mention it so you know the context I am in , but I believe it should be solvable also for people who have no know... | var hWnd = ( IntPtr ) WordUtils.GetHwnd ( ) ; var processId = Process.GetCurrentProcess ( ) .Id ; var uiApp = TestStack.White.Application.Attach ( ( int ) processId ) ; var uiWindow = uiApp.GetWindow ( WindowHandling.GetWindowText ( hWnd ) , InitializeOption.NoCache ) ; var wf = ( IUIItemContainer ) uiWindow.Get ( Sear... | Calculate new ScrollPercent - after ViewSize changed |
C# | As explained in this question , and these articles , the following is not allowed : Because if it was , and you had this : and then : This is illegal because even though B 's access to X means it knows that C has the desired signature it 's still not allowed to actually access the member.So far , so good . But given th... | public class A { protected virtual int X { get ; private set ; } } public class B : A { public int Add ( A other ) { return X + other.X ; } } public class C : A { protected override int X { get { return 4 ; } } } A c = new C ( ) ; B b = new B ( ) ; b.Add ( c ) ; public class A { protected virtual int X { get ; private ... | Why can parents access instances of child class ' protected members , if siblings ca n't ? |
C# | When I write this code in VS , it does n't work ( `` Can not implicitly convert 'int ' to 'short ' . An explicit conversion exists . Are you missing a cast ? `` ) : Yet this code is absolutely fine : I know I can make the error go away by casting the entire expression as a short , but can anyone tell me why this happen... | short A = 5 ; short B = 1 < < A ; short A = 1 < < 5 ; | Bitshifting Int16 's only works with literals |
C# | I 'm using a third party library which contains a bunch of extension methods on top of IQueryable . To use these extension methods i do n't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.This is so that i can switch it out the library som... | namespace MyProject.Extensions { public static class IQueryableExtension { public static IQueryable < T > Fetch < T , K > ( this IQueryable < T > queryable , Expression < Func < T , K > > selector ) { return queryable.Fetch ( selector ) ; } } } | Extension Methods - Changing the Namespace |
C# | I have got a struct : And now I can do : It seems the compiler is smart enough to convert Decibel to double , and then use the < operator for doubles ? I had different struct named Duration , which was wrapping TimeSpan . It had implicit conversions for TimeSpan to/from Duration , but the < and > operators are not work... | public struct Decibel { public readonly double Value ; public Decibel ( double value ) { Value = value ; } public static implicit operator Decibel ( double decibels ) { return new Decibel ( decibels ) ; } public static implicit operator double ( Decibel decibels ) { return decibels.Value ; } } bool x = new Decibel ( 0 ... | What implicit conversions are supported when using < and > operators ? |
C# | I have changed the following SystemColors already : I 'm not sure what to call it , but which SystemColor is responsible for what I 'm calling the : `` InactiveSelectedItem '' ? It changes to this color every time I lose focus on the SelectedItem . Would be nice if someone could help me . I used blend already to check ... | < ! -- Background of selected item when focussed -- > < SolidColorBrush x : Key= '' { x : Static SystemColors.HighlightBrushKey } '' Color= '' Transparent '' / > < ! -- Background of selected item when not focussed -- > < SolidColorBrush x : Key= '' { x : Static SystemColors.ControlBrushKey } '' Color= '' Transparent '... | ListBox SystemColor for Inactive Item ? |
C# | I just found out that it is possible to use the keyword var as a class name : Now if I overload the implicit cast operator I can use my class in an interesting manner : In such scenario , is it still possible to somehow make the compiler infer the types ? This blog entry states that it is not possible ( go to the parag... | public class var // no problem here { } namespace MyApp { class Program { static void Main ( string [ ] args ) { var x = 1 ; // var is of type MyApp.var } } public class var { public implicit operator var ( int i ) { return new var ( ) ; } } } | Can you take advantage of implicit type variables with a class named ` var ` ? |
C# | I would like to find a way to check to see if a set of values are contained in my variable.I am a transplant to .NET from Delphi . This is fairly easy code to write in Delphi , but I am not sure how to do it in C # . | [ Flags ] public enum Combinations { Type1CategoryA = 0x01 , // 00000001 Type1CategoryB = 0x02 , // 00000010 Type1CategoryC = 0x04 , // 00000100 Type2CategoryA = 0x08 , // 00001000 Type2CategoryB = 0x10 , // 00010000 Type2CategoryC = 0x20 , // 00100000 Type3 = 0x40 // 01000000 } bool CheckForCategoryB ( byte combinatio... | Set In enum for C # |
C# | I 've run my code through code coverage and the line below shows 1 block as not covered.Can anyone tell me which part of that line is n't executing ? An Example to play with : and the test method | public abstract class Base { public abstract IExample CreateEntity < TExample > ( ) where TExample : IExample , new ( ) ; } public class Class1 : Base { public override IExample CreateEntity < TExample > ( ) { IExample temp = new TExample ( ) ; return temp ; } } public interface IExample { } public class TEx : IExample... | Creation of a new instance of generic type parameter not getting code coverage |
C# | Targeting .net 4.0 , I 'm trying to build the following classes : As the code comment above indicates , the compiler gives an error : Can not implicitly convert type 'Shared.Configuration.ConfigurationElementCollection < TElement , TParent > ' to 'Shared.Configuration.ConfigurationElementCollection < Shared.Configurati... | public class ConfigurationElementCollection < TElement , TParent > where TElement : ParentedConfigElement < TParent > , new ( ) where TParent : class { public TParent ParentElement { get ; set ; } protected ConfigurationElement CreateNewElement ( ) { //************************************************** //COMPILER GIVES... | Invalid Cast of Type Constrained C # Generic |
C# | Here is my test code : the extension method GetInstructions is from here : https : //gist.github.com/jbevain/104001Here is run result as the screenshot shown : NON-ASYNC calls got correct generic parameters , but ASYNC calls can not .My question is : where are the generic parameters stored for ASYNC calls ? Thanks a lo... | using System ; using System.Linq ; using System.Reflection ; using System.Threading.Tasks ; namespace ConsoleApp1 { class Program { static void Main ( string [ ] args ) { typeof ( TestClass ) .GetMethods ( ) .Where ( method = > method.Name == `` Say '' || method.Name == `` Hello '' ) .ToList ( ) .ForEach ( method = > {... | Where are the generic parameters saved for Async calls ? Where to find its name or other information ? |
C# | How could I write this C # code in F # or Haskel , or a similar functional language ? | var lines = File.ReadAllLines ( @ '' \\ad1\\Users\aanodide\Desktop\APIUserGuide.txt '' ) ; // XSDs are lines 375-471var slice = lines.Skip ( 374 ) .Take ( 471-375+1 ) ; var kvp = new List < KeyValuePair < string , List < string > > > ( ) ; slice.Aggregate ( kvp , ( seed , line ) = > { if ( line.StartsWith ( `` https ''... | How does this C # code get done in functional languages ( F # ? Haskel ? ) |
C# | I have a DataGrid simplified looking like this : My ViewModel looks something like this : Now I want changes to datagrid cells being stored immediately to the database . How to do that in MVVM ? Currently I listen to the OnCellEditEnding event of the DataGrid and save the record in the code-behind . But that is pretty ... | < DataGrid AutoGenerateColumns= '' False '' ItemsSource= '' { Binding Parts } '' SelectedItem= '' { Binding SelectedPart } '' > < DataGrid.Columns > < DataGridTextColumn Header= '' Name '' Binding= '' { Binding Path=Name , Mode=TwoWay } '' / > < DataGridTemplateColumn Header= '' PartType '' > < DataGridTemplateColumn.C... | WPF DataGrid : Save cell changes immediately with MVVM |
C# | I am wondering if it makes any sense to have both `` class '' and `` new ( ) '' constraints when defining a generic class . As in the following example : Both constraints specify that T should be a reference type . While the `` class '' constraint does not imply that a implicit constructor exists , the `` new ( ) '' co... | class MyParanoidClass < T > where T : class , new ( ) { //content } | Is it pointless to have both `` class '' and `` new ( ) '' constraints in a generic class ? |
C# | I 've seen several articles talking about not generating too many System.Random instances too closely together because they 'll be seeded with the same value from the system clock and thus return the same set of numbers : https : //stackoverflow.com/a/2706537/2891835https : //codeblog.jonskeet.uk/2009/11/04/revisiting-... | Random [ ] randoms = new Random [ 1000 ] ; for ( int i = 0 ; i < randoms.Length ; i++ ) { randoms [ i ] = new Random ( ) ; } // use Random instances and they 'll all have distinct generated patterns | Do multiple instances of System.Random still use the same seed in .Net Core ? |
C# | I 'm currently working through the Pluralsight C # 5.0 course , and I 'm relatively new to programming.I previously thought I understood the concept of Data Types on a basic level , Int/Array/Strings etc.In this course it starts to introduce C # 's huge emphasis on Types , and creating your own custom types.One of the ... | GradeStatistics stats = book.ComputeStatistics ( ) ; namespace Grades { public class GradeStatistics { public GradeStatistics ( ) { HighestGrade = 0 ; LowestGrade = float.MaxValue ; } public float AverageGrade ; public float HighestGrade ; public float LowestGrade ; } } public GradeStatistics ComputeStatistics ( ) { Gr... | Type confusion : A type is class , a variable and an object ? |
C# | I have a recording program that stays TopMost all the time except when I open a Modern app ( Windows 8 ) or the Start Screen.It is possible to make a desktop application stay on top of modern apps , like the Magnifying Glass tool : Now , the problem is that using the TopMost option and/or the API call in a WPF window w... | static readonly IntPtr HWND_TOPMOST = new IntPtr ( -1 ) ; static readonly IntPtr HWND_NOTOPMOST = new IntPtr ( -2 ) ; static readonly IntPtr HWND_TOP = new IntPtr ( 0 ) ; static readonly IntPtr HWND_BOTTOM = new IntPtr ( 1 ) ; const UInt32 SWP_NOSIZE = 0x0001 ; const UInt32 SWP_NOMOVE = 0x0002 ; const UInt32 TOPMOST_FL... | Top most even for Modern Apps |
C# | I am attempting to create a serialization interface ( similar to Cocoa 's NSCoding protocol ) so that I can get a quick binary representation of a class to send across a network or store in a database . However , some cases ( especially involving image encoding ) have many async-only methods that require awaiting . How... | public async static Task < byte [ ] > Serialize ( this IList < ISerializable > list ) { using ( Archiver archiver = new Archiver ( ) ) { archiver.Write ( list.Count ) ; foreach ( ISerializable value in list ) { await archiver.Write ( value ) ; } return archiver.Result ; } } | How can I handle an interface method that may or may not be async ? |
C# | Let 's say we have : Then we 'd like to instantiate Foo with an object initializer : The syntax of initializing BarPropertyInA baffles me , because the code compiles without warnings and , when run , throws NullReferenceException . I do n't recognize that syntax , but it seems to have the same effect when used with a f... | class Foo { public int IntPropertyInFoo { get ; set ; } public Bar BarPropertyInA { get ; set ; } } class Bar { public string StringPropertyInBar { get ; set ; } } public static void Main ( string [ ] args ) { var foo = new Foo { IntPropertyInFoo = 123 , BarPropertyInA = // Ommiting new and type name - why does it comp... | Unrecognized C # syntax |
C# | I 've two similar projects . One is a Silverlight project and the other one a WPF . Both of them containing some namespaces and plenty of custom user controls . As the controls are distributed over many namespaces , I have to define quite a few namespaces , when I 'm using them . So I started to define the XML namespac... | [ assembly : XmlnsPrefix ( `` http : //ui.example.com/xaml/touch '' , `` cui '' ) ] [ assembly : XmlnsDefinition ( `` http : //ui.example.com/xaml/touch '' , `` example_ui.controls '' ) ] [ assembly : XmlnsDefinition ( `` http : //ui.example.com/xaml/touch '' , `` example_ui.themes '' ) ] xmlns : cui= '' http : //ui.ex... | Why is XAML ( WPF ) not searching in my XML namespace definitions for the controls ? |
C# | I 've been looking into Entity Framework 7 source code on github and I 've found following property initialization in TableExpressionBase.csI have never seen such usage of = > operator in C # . I 've also looked what is new in C # 6.0 , however I have n't found this construct . Can someone explain what is the purpose o... | public override ExpressionType NodeType = > ExpressionType.Extension ; | Initialization with = > ( such that ) |
C# | I have a list of Func defining an ordering : I can order the results with something like ... I 'm trying to figure how to do the above when the list can contain any number of sequential orderings . Is it possible ? | var ordering = new List < Func < Person , IComparable > > { x = > x.Surname , x = > x.FirstName } ; people = people.OrderBy ( ordering [ 0 ] ) .ThenBy ( ordering [ 1 ] ) ; | Linq to Objects ordering by arbitrary number of parameters |
C# | I was working on a solution with multiple projects and I updated Newtonsoft.Json in a one of the projects ( a class library ) . This caused some errors in another project ( an ASP.Net WebApi project ) because it also needed the reference to Newtonsoft.Json to be updated . The error was thrown at run-time not compile-ti... | Install-Package Newtonsoft.Json | How to ensure that all projects in a c # solution use same versions of third party library ? |
C# | I am using LINQ .Find ( ) and it 's not stopping when it finds a match . I have : Any ideas ? I 'm going nuts over here.Thanks ! | List < ipFound > ipList = new List < ipFound > ( ) ; ipFound ipTemp = ipList.Find ( x = > x.ipAddress == srcIP ) ; if ( ipTemp == null ) { // this is always null } public class ipFound { public System.Net.IPAddress ipAddress ; public int bytesSent ; public int bytesReceived ; public int bytesTotal ; } | c # : Not finding object in list |
C# | Here 's the story so far : I 'm doing a C # winforms application to facilitate specifying equipment for hire quotations.In it , I have a List < T > of ~1500 stock items.These items have a property called AutospecQty that has a get accessor that needs to execute some code that is specific to each item . This code will r... | [ some code to get the following items from the list here ] if ( Item0002.Value + Item0003.Value > Item0004.Value ) { return Item0002.Value } else { return Item0004.Value } | c # executing a string as code ... is it worth the effort ? |
C# | I have a C # application that calls : It is set to target x86 , and when I run it I can see from Task Manager that it is a 32-bit process . However that line of code is strangely going to the 64-bit hive at HKCU\Software\MyApp , instead of the 32-bit hive at HKCU\Software\Wow6432Node\MyApp . Any ideas ? I also started ... | Microsoft.Win32.Registry.CurrentUser.OpenSubKey ( @ '' Software\MyApp '' ) get-itemproperty -Path Registry : :HKEY_CURRENT_USER\Software\MyApp | Why does my 32-bit application not access the 32-bit registry hive ? |
C# | I have the following regex : I 'm using it to find matches within a string : This used to yield the results I wanted ; however , my goal has since changed . This is the desired behavior now : Suppose the string entered is 'stuff/ { thing : aa/bb/cccc } { thing : cccc } ' I want formatTokens to be : Right now , this is ... | @ '' { thing : ( ? : ( ( \w ) \2* ) ( [ ^ } ] * ? ) ) + } '' MatchCollection matches = regex.Matches ( string ) ; IEnumerable formatTokens = matches [ 0 ] .Groups [ 3 ] .Captures .OfType < Capture > ( ) .Where ( i = > i.Length > 0 ) .Select ( i = > i.Value ) .Concat ( matches [ 0 ] .Groups [ 1 ] .Captures.OfType < Capt... | Regex and proper capture using .matches .Concat in C # |
C# | I have some XMLs that represent permutation between for example , members of 4 sets ( A , B , C , D ) . Suppose that A= { A1 , A2 } , B= { B1 } , C= { C1 , C2 } and D= { D1 , D2 , D3 } but current XML is not normal because this members combined in non-regular way in each answer . `` set '' Attribute shows name of set a... | < root > < phrase permutation=ABCD > < ans number=1 > < word set=A member=A1/ > < word set=A member=A2/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D2/ > < /ans > < ans number=2 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=C member=C2/ > < word... | XML Elements Normalizing |
C# | For serialization purpose , we are trying to generate the delegate to update some object property values on the fly and store them into a list for further use.Everything works quite well as long as we do not try to deserialize structs.We based our code on this article about open delegate : http : //codeblog.jonskeet.uk... | private static System.Action < object , object > ToOpenActionDelegate < T , TParam > ( System.Reflection.MethodInfo methodInfo ) where T : class { System.Type parameterType = typeof ( TParam ) ; // Convert the slow MethodInfo into a fast , strongly typed , open delegate System.Action < T , TParam > action = ( System.Ac... | Using Open Delegate to access a struct property setter generate exception |
C# | I have an expression that I use a few times in several LINQ queries so I separated it out into it 's own method that returns the expression . The lambda portion of the function is kind of messy looking . Anyone want to take a crack at refactoring it and making it more readable and/or smaller ? A quick English descripti... | private Expression < Func < Message , bool > > UserSelector ( string username , bool sent ) { return x = > ( ( sent ? x.FromUser : x.ToUser ) .Username.ToLower ( ) == username.ToLower ( ) ) & & ( sent ? ! x.SenderDeleted : ! x.RecipientDeleted ) ; } /// < summary > /// Expression to determine if a message belongs to a ... | How might I clean up this lambda ? |
C# | I just answered a question about whether a Task can update the UI . As I played with my code , I realized I 'm not clear myself on a few things.If I have a windows form with one control txtHello on it , I 'm able to update the UI from a Task , it seems , if I immediately do it on Task.Run : However if I Thread.Sleep fo... | public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Task.Run ( ( ) = > { txtHello.Text = `` Hello '' ; } ) ; } } public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Task.Run ( ( ) = > { Thread.Sleep ( 5 ) ; txtHello.Text = `` Hello '' ; //kaboom } ) ; } } | Background Task sometimes able to update UI ? |
C# | I am using DirectShowLib-2005 - DxSnap example to display and capture the image from Webcam.Everything works fine with the example.But when i try to merge it with my application ( i tried to call that form from my main form ) it is working for the first time . Once i close and open the capture window , it is not displa... | public partial class frmMain : Form { public frmMain ( ) { InitializeComponent ( ) ; } /// < summary > /// The main entry point for the application . /// < /summary > [ STAThread ] private static void Main ( ) { Application.Run ( new frmMain ( ) ) ; } private void button1_Click ( object sender , EventArgs e ) { frmdxSn... | Dxsnap not displaying the video properly after first time open |
C# | I 'm ( now ) trying to use ANTLR4 and C # to design a language , and so far I 've been fiddling around with it . In the process , I decided to try and create a simple mathematical expression evaluator . In the process , I created the following ANTLR grammar for it : When I try to generate C # code from it using this co... | grammar Calculator ; @ parser : :members { protected const int EOF = Eof ; } @ lexer : :members { protected const int EOF = EOF ; protected const int HIDDEN = Hidden ; } program : expr+ ; expr : expr op= ( '* ' | '/ ' ) expr | expr op= ( '+ ' | '- ' ) expr | INT | ' ( ' expression ' ) ' ; INT : [ 0-9 ] + ; MUL : '* ' ;... | What are these odd errors that occur when I attempt to generate C # with ANTLR4 ? |
C# | Usually , I like the challenges of regular expressions and even better - solving them.But it seems I have a case that I ca n't figure out.I have a string of values that are separated by a semi-colon like CSV line that can look like this one:123-234 ; FOO-456 ; 45-67 ; FOO-FOO ; 890 ; FOO-123 ; 11-22 ; 123 ; 123 ; 44-55... | 123-23445-6789011-22123098-567 | How to match both numbers and range of numbers in a CSV-like string with regex ? |
C# | I am a developer who works primarily with embedded devices ( programmed with C and assembly ) . My C # and OOP knowledge is very limited ( although I can fake my way through it when necessary ) . I have five devices that interface with a PC via USB . The PC does some calculations and sends a result to the device . The ... | class Device //This is what EVERY device can do { ... DoWork1 ( ) ; DoWork2 ( ) ; DoWork3 ( ) ; ... } class Device1 { ... DoWork1 ( ) ; //This is how the work is done for this deviceDoWork2 ( ) ; DoWork3 ( ) ; ... } class Device2 { ... DoWork1 ( ) ; //This is how the work is done for this device ( not the same way as D... | How would one implement many classes that have the same methods that do things different ? |
C# | C # 2008 SP1I have created an updater for our clients application . The way the updater works is to download all the updated files and store them in a temporary folder then check the file hashes . If everything is ok it will copy the files to the applications installation folder . Once this is been completed it will de... | Environment.SpecialFolder . | How do I get a path suitable for storing temporary files ? |
C# | I have a class that instantiates two classes which implement interfaces . I want one class to notify another class that something is OK . I could do it with an Action and then use private variables in the class but wondered if there was a direct way of doing it with properties so that when a property 's value changes i... | public class MyClass { public ILogger Logger { get ; set ; } public ILogic Logic { get ; set ; } private Form MyWinform ; public void Setup ( ) { MyWinform = new MyWinform ( ) ; MyWinform.StartBatch += Logger.CreateFile ; //Create file when user presses start //How can I set a property on ILogic to be AllOk once ILogge... | Action < T > equivalent for properties |
C# | I am trying to write an extension method that checks if an object is sub class of T.Here is what I did , but not accepted by visual studio.Any idea how can i write this ? | public static bool IsChildOf < T > ( this object obj ) { return ( typeof ( obj ) .IsSubclassOf ( typeof ( T ) ) ) ; } [ Test ( ) ] public void IsChildOfTest ( ) { var dog = new Dog ( ) ; var isAnimal = dog.IsChildOf < Animal > ( ) ; Assert.That ( isAnimal ) ; } | Extension method to check if an object is sub class of T |
C# | Question 1 > Should I check NULL in the following case ? Question 2 > I just start to transfer to C # from C++.When coding in C++ , I know when the checking should be done.However , I am totally lost in the C # world . So the question is : is therea general rule that can tell me when I MUST check for NULL ? Thank you | public interface INewClass { } public class NewClass : INewClass { } public void FunMeA ( INewClass obj ) { NewClass n = ( NewClass ) obj ; ... // Should I check ( n == null ) here ? // call methods defined inside INewClass ( updated from NewClass to INewClass ) ... } A concrete example , public void FunMeB ( IAsyncRes... | Should we check NULL when cast IClass to Class ? |
C# | I have the enum structure as follows : Now I want to get a list of MyEnum , i.e. , List < MyEnum > that contains all the One , Two Three . Again , I am looking for a one liner that does the thing . I came out with a LINQ query but it was unsatisfactory because it was a bit too long , I think : A better suggestion ? | public enum MyEnum { One=1 , Two=2 , Three=3 } Enum.GetNames ( typeof ( MyEnum ) ) .Select ( exEnum = > ( MyEnum ) Enum.Parse ( typeof ( MyEnum ) , exEnum ) ) .ToList ( ) ; | Get a List of available Enums |
C# | I have two classes.Class A : And Class B : They do n't share the same interface or abstract class.A and B have two distinct hierarcy and I ca n't change that at the moment.I want to write a single procedute that works for A and B and use QQ and WW methods.Can I do that ? Can you suggest any document I can study ? Tanks | class A ( ) { public void QQ ( ) { } public void WW ( ) { } } class B ( ) { public void QQ ( ) { } public void WW ( ) { } } | two class with common methods and properties |
C# | In one sentence , what i ultimately need to know is how to share objects between mid-tier functions w/ out requiring the application tier to to pass the data model objects.I 'm working on building a mid-tier layer in our current environment for the company I am working for . Currently we are using primarily .NET for pr... | main { MidTierServices.UpdateCustomerName ( `` testaccount '' , `` John '' , `` Smith '' ) ; // since the data takes up to 4 seconds to be replicated from // write server to read server , the function below is going to // grab old data that does not contain the first name and last // name update ... . John Smith will b... | Mid-Tier Help Needed |
C# | While I 'm working on parallelism of our framework , I 've confronted a strange condition which I ca n't imagine why ! I simplified the situation to describe it easy.consider this code : which the personList is shared between multiple threads.In what circumstances is it possible for person to be null and I get the Null... | foreach ( var person in personList ) { if ( person.Name == `` Mehran '' ) break ; } | Modification of a local variable to null , via another thread , how is that possible |
C# | I use recursive function to do somethingSo , I want that tbOut.Text = `` Done ! `` ; will be done only after all iterations ends . At now it 's happenning at the same time while iterations under process . If I run this function like thatthe result still the same . How to wait when this function will ends completely ? | public async void walk ( StorageFolder folder ) { IReadOnlyList < StorageFolder > subDirs = null ; subDirs = await folder.GetFoldersAsync ( ) ; foreach ( var subDir in subDirs ) { var dirPath = new Profile ( ) { FolderPath = subDir.Path } ; db.Insert ( dirPath ) ; walk ( subDir ) ; } tbOut.Text = `` Done ! `` ; } walk ... | How to wait all asynchronous operations ? |
C# | I am not exactly sure how to make this question readable/understandable , but hear my out and I hope you will understand my issue when we get to the end ( at the very least , it is easily reproduceable ) .I try to call a method used for validating results in UnitTests . It has the following signature : What this means ... | void AssertPropertyValues < TEnumerable , TElement , TProperty > ( TEnumerable enumerable , Func < TElement , TProperty > propertyPointer , params TProperty [ ] expectedValues ) where TEnumerable : System.Collections.Generic.IList < TElement > AssertPropertyValues ( item.ItemGroups , itemGroup = > itemGroup.Name , `` N... | Why does method type inference fail to infer a type parameter ? |
C# | I am creating my first ASP.NET MVC project . I have started with connecting TFS and adding bugs in to TFS via C # .This code shown above works fine . But is it possible to achieve same result using a SQL Server stored procedure ? Is there any way to connect to TFS and add bug in to TFS using a stored procedure ? I have... | var tfsURI = new Uri ( `` http : //test:8080/tfs '' ) ; var networkCredential1 = new NetworkCredential ( `` test '' , `` test ! `` ) ; ICredentials credential = ( ICredentials ) networkCredential1 ; Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCred... | Calling Team Foundation Server ( TFS ) APIs via SQL Server stored procedure |
C# | I 'm working with some legacy code right now which usually used try + catch in combination with Convert.ToDecimal ( someString ) ( for instance ) to try and convert strings to decimals . For some reasons I have to use the setting that - when debugging - I stop at every thrown exception ( not only user-unhandled ones ) ... | try { Convert.ChangeType ( val , targetType ) ; } catch { // Do something else } | More elegant way of finding out if I can convert a value into a certain type |
C# | In the following method , Does the use of const provide any benefit over just declaring the string as a string ? Woudl it not be interned anyway ? | public void InspectList ( IList < int > values ) { if ( values ! = null ) { const string format = `` Element At { 0 } '' ; foreach ( int i in values ) { Log ( string.Format ( format , i ) ) ; } } } | Use of const in a method |
C# | I am developing a website in which I 'm using forms authentication.We have 2 log in pages : one for user , another for admin.I added this code into webconfig file for user.I am using this code for user side when user successfully logged in.I am not using the default user membership database . I have my own database in ... | < forms loginUrl= '' Login.aspx '' defaultUrl= '' Home.aspx '' > FormsAuthentication.RedirectFromLoginPage ( UserName.Text , chkPersistCookie.Checked ) | Forms Authentication for different roles ? |
C# | I have multiple projects in my solution , all .NET Core 3.1 . One of them is my core project ( “ A Project ” ) where I just have basic model classes with no methods or database access . For demonstration purposes , below are simplified versions of my Address.cs and User.cs files : In another project ( “ B Project ” ) ,... | public class Address { public int Id { get ; set ; } public string AddressText { get ; set ; } public virtual User User { get ; set ; } } public class User { public int UserId { get ; set ; } public int UserName { get ; set ; } public ICollection < Address > { get ; set ; } } | Inherit ( ? ) IdentityUser from another project |
C# | The following C # function : compiles unsurprisingly to this : But the equivalent F # function : compiles to this : ( Both are in release mode ) . There 's an extra nop at the beginning which I 'm not too curious about , but the interesting thing is the extra ldnull and tail . instructions.My guess ( probably wrong ) i... | T ResultOfFunc < T > ( Func < T > f ) { return f ( ) ; } IL_0000 : ldarg.1 IL_0001 : callvirt 05 00 00 0A IL_0006 : ret let resultOfFunc func = func ( ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldnull IL_0003 : tail . IL_0005 : callvirt 04 00 00 0A IL_000A : ret | What is the purpose of the extra ldnull and tail . in F # implementation vs C # ? |
C# | Can you clarify me why in this piece of code : I get the error : `` Only assignment , call , increment , decrement , and new object expressions can be used as a statement . `` IView defines the ShowDialog ( ) method . | private Dictionary < Type , Type > viewTypeMap = new Dictionary < Type , Type > ( ) ; public void ShowView < TView > ( ViewModelBase viewModel , bool showDialog = false ) where TView : IView { var view = Activator.CreateInstance ( viewTypeMap [ typeof ( TView ) ] ) ; ( IView ) view.ShowDialog ( ) ; } | Can not perform explicit cast |
C# | My Project : Web API project - ASP .NET Framework 4.8Problem ? The code flow is as follows:1 . ) The API is called - > it must call another API - > 2 . ) Get JWT authentication token - > 3 . ) Calls the desired method.The problem is if my API is called 100 times , I will make 100 calls for the GetJwtToken ( ) method an... | if ( response.StatusCode == HttpStatusCode.Unauthorized ) | Best practices for managing Web API JWT token in another Web API |
C# | I 'm using Visual Studio 2010 SP1 , Target framework is 2.0 , Platform target : Any CPU , testing under Windows 7 x64 SP1.I 'm experiencing strange performance behavior.Without an app.config , or with the following app.config , it makes my program run slowly ( Stopwatch shows ~0.11 s ) The following app.config makes my... | < ? xml version= '' 1.0 '' ? > < configuration > < startup > < supportedRuntime version= '' v2.0.50727 '' / > < /startup > < /configuration > < ? xml version= '' 1.0 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0.30319 '' sku= '' .NETFramework , Version=v4.0 '' / > < /startup > < /configuratio... | Strange performance behavior |
C# | I 'm trying to build a framework that allows people to extend our core functionality by implementing an interface . Below is a dumbed down example of this interface.Recently , we 've decided to modify this interface ( I know I should n't break dependent code , but the truth is we do n't have any 3rd parties implementin... | public interface MyInterface { IData GetData ( string p1 , char p2 , double p3 ) ; } public interface MyInterface { IData GetData ( string p1 , char p2 , double p3 , bool p4 , DateTime p5 ) ; } public class MyParameters { public bool p4 { get ; set ; } public DateTime p5 { get ; set ; } } public interface MyInterface {... | Method Parameters vs Parameter Object |
C# | Is there a different way to do what I want to do here ? If there 's not , I do n't really see all that much point in implicit types ... | var x = new { a = `` foobar '' , b = 42 } ; List < x.GetType ( ) > y ; | Why ca n't I do this with implicit types in C # ? |
C# | I have my code which makes a webservice Call based on type of request . To do that , I have following code ; So as per open close principle , I can subclass like : Now my client class will look something like this : Now , I still have to use if and else , and will have to change my code if there are any new request typ... | public class Client { IRequest request ; public Client ( string requestType ) { request = new EnrolmentRequest ( ) ; if ( requestType == `` Enrol '' ) { request.DoEnrolment ( ) ; } else if ( requestType == `` ReEnrol '' ) { request.DoReEnrolment ( ) ; } else if ( requestType == `` DeleteEnrolment '' ) { request.DeleteE... | How to resolve type at run time to avoid multipe if else |
C# | Just i have a bit of confusion in understanding static reference.incase of instance reference we can understand when i declare What if the case of Static class ? can i mean it when i declareUpdate : Since class is blueprint and objects are physical entities ; Incase of static class when i declare staticClass.MyMethod o... | Car myCar = new Car ( ) ; Car yourCar = new Car ( ) ; -- -- -- -- -- -- -- - -- -- -- -- -- -- -- stack Managed Heap -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -myCar -- -- -- - > points to Car -- -- -YourCar -- -- -- - > points to Car -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - staticClass.MyMethod... | C # - Static class call means `` content at address ? `` |
C# | In an Interview , Interviewer asked to me.. thatI have a code which written in side the try and catch block likesuppose we got an error on code line 3then this will not go in the catch blockbut If I got error on any other line except line 3 it go in catch blockis this possible that if error occur on a particular line t... | try { //code line 1 //code line 2 //code line3 -- if error occur on this line then did not go in the catch block //code line 4 //code line 5 } catch ( ) { throw } | On Error catch block did not call |
C# | This question is about when you do and do n't need to include generic type specification arguments . It 's a bit lengthy , so please bear with it.If you have the following ( contrived ) classes ... The following method ... Can be called with or without having to specify the type argument TUser ... So far , so good.But ... | public abstract class UserBase { public void DoSomethingWithUser ( ) { } } public class FirstTimeUser : UserBase { /* TODO : some implementation */ } private static void DoThingsWithUser < TUser > ( TUser user ) where TUser : UserBase { user.DoSomethingWithUser ( ) ; } var user = new FirstTimeUser ( ) ; DoThingsWithUse... | Generic type specification arguments - sometimes optional , but not always |
C# | With great surprised I observed the following behavior today : Given a classand this codewhile initializing foos to new List < Foo > { new Foo ( ) , new Foo ( ) , new Foo ( ) } makes the loop write `` 555 '' .My question : Why does this happen and is there a way to circumvent this whithout using .ToList ( ) ( which nee... | class Foo { prop int FooNumber { get ; set ; } } IEnumerable < Foo > foos = Enumerable.Range ( 0,3 ) .Select ( new Foo ( ) ) ; foreach ( var foo in foos ) foo.Bar = 5 ; foreach ( var foo in foos ) Console.Write ( foo.Bar ) ; // Writes 000 | Changing Properties of IEnumerator < T > .Current |
C# | I have the following method signature : The delegate and the arguments are saved to a collection for future invoking.Is there any way i can check whether the arguments array satisfies the delegate requirements without invoking it ? Thanks.EDIT : Thanks for the reflection implementation , but i searching for a built-in ... | public static void InvokeInFuture ( Delegate method , params object [ ] args ) { // ... } | Checking whether an ` object [ ] args ` satisfies a Delegate instance ? |
C# | VB.NET Code : Returns : 113,25 : -163,5C # Code : returns 0 : 0I do n't get it , would appreciate an explanation . | Module Module1Sub Main ( ) Dim x , y As Single x = 0 + ( 512 / 2 - 407 ) / 256 * 192 * -1 y = 0 + ( 512 / 2 - 474 ) / 256 * 192 Console.WriteLine ( x.ToString + `` : `` + y.ToString ) Console.ReadLine ( ) End SubEnd Module class Program { static void Main ( string [ ] args ) { float x , y ; x = 0 + ( 512 / 2 - 407 ) / ... | Why is this code returning different values ? ( C # and VB.NET ) |
C# | I 'd like to enforce a struct to always be valid regarding a certain contract , enforced by the constructor . However the contract is violated by the default operator.Consider the following , for example : As a workaround I changed my struct to a class so I can ensure the constructor is always called when initializing ... | struct NonNullInteger { private readonly int _value ; public int Value { get { return _value ; } } public NonNullInteger ( int value ) { if ( value == 0 ) { throw new ArgumentOutOfRangeException ( `` value '' ) ; } _value = value ; } } // Somewhere else : var i = new NonNullInteger ( 0 ) ; // Will throw , contract resp... | How can I enforce a contract within a struct |
C# | What is going on with this C # code ? I 'm not even sure why it compiles . Specifically , what 's going on where it 's setting Class1Prop attempting to use the object initializer syntax ? It seems like invalid syntax but it compiles and produces a null reference error at runtime . | void Main ( ) { var foo = new Class1 { Class1Prop = { Class2Prop = `` one '' } } ; } public class Class1 { public Class2 Class1Prop { get ; set ; } } public class Class2 { public string Class2Prop { get ; set ; } } | What is happening with this C # object initializer code ? |
C# | Wracking my brain around this to no avail , wonder if anyone can be of help ? Getting a really frustrating casting issue that im sure will have a quick answer , but is probably just happening due to my limited understanding of generic type inference or something.Thanks in advance ! Scenario is a number of `` Step '' Vi... | public interface IStepViewModelBuilderFactory { IStepModelBuilder < T > Create < T > ( T stepViewModel ) where T : IStepViewModel ; void Release < T > ( IStepModelBuilder < T > stepViewModelBuilder ) where T : IStepViewModel ; } public interface IStepViewModel { } public interface IStepModelBuilder < TStepViewModel > :... | ViewModelBuilder generics casting issue |
C# | I have recently noticed a curiosity ( at least for me ) . I thought that the null-coalescing operator would take the precedence over any mathematical operation but obviously i was wrong . I thought following two variables would have the same value at the end : But v2.Value is ( the desired ) 1 whereas v1.Value is still... | double ? previousValue = null ; double ? v1 = 1 + previousValue ? ? 0 ; double ? v2 = 1 + ( previousValue ? ? 0 ) ; | Why do i need to put the null-coalescing operator in brackets ? |
C# | Within an async method , any local variables are stored away so that when whatever thread continues after the await will have access to the values . Is there any way to indicate which values are really needed after the await ? For example : So I have declared 7 local variables , but only use 2 of them after the await ,... | var firstName = `` Karl '' ; var lastName = `` Anderson '' ; var street1 = `` 123 Nowhere Street '' ; var street2 = `` Apt 1-A '' ; var city = `` Beverly Hills '' ; var state = `` California '' ; var zip = `` 90210 '' ; await MyTaskHere ( ) ; Console.WriteLine ( firstName ) ; Console.WriteLine ( city ) ; | Can I specify which variables I want to persist beyond the completion of an await continuation ? |
C# | I was trying to implement the following FFT filter kernel : This formula is missing with two squares under the sqrt.Source codeOnly concentrate on the algorithm and the formula at this time.OutputThe problem with this filter is , it can only rotate between 0-90 degrees , and does n't work outside that range.How can I m... | public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Bitmap image = DataConverter2d.ReadGray ( StandardImage.LenaGray ) ; Array2d < double > dImage = DataConverter2d.ToDouble ( image ) ; int newWidth = Tools.ToNextPowerOfTwo ( dImage.Width ) * 2 ; int newHeight = Tools.ToNextPowerOfTwo ( dIm... | Band-pass filter ca n't rotate more than 90 degrees |
C# | I want to be able to initialize a class just like I initialize a string : I really do n't know what exactly string str = `` hello '' ; does . I assume `` hello '' gets translated by the compiler into new System.String ( `` hello '' ) ; but I 'm not sure . Maybe is just not possible or maybe I 'm missing something very ... | string str = `` hello '' ; MyClass class = `` hello '' ; class StringOnFile { private static string Extension = `` .htm '' ; private string _FullPath ; public bool Preserve = false ; public string FullPath { get { return _FullPath ; } } public static implicit operator StringOnFile ( string value ) { StringOnFile This =... | How can I make a class in C # that I can initialize just like a string ? |
C# | If I haveandIs this the same ? Is the compiler able to remove s ? How about ? Thanks . | private string Foo ( string decrypted ) { return decrypted.Substring ( blah ) ; } private string Foo ( string decrypted ) { string s = decrypted.Substring ( blah ) ; return s ; } private string Foo ( string decrypted ) { string s = decrypted.Substring ( blah ) ; string t = s ; return t ; } | compiler optimisation when returning strings |
C# | I have a working real time monitoring program but it 's class architecture is too complex . And this disturbs me really much . Let me start by explaining the program.User InteractionThis is a monitoring program with user interaction . Which means , user can select different dimensions , different metrics , include them... | Req Success OrderFunction 5 60ms WebServer2Req Failed OrderFunction 2 176ms WebServer5Resp Success SuggestFunction 8 45ms WebServer2 | Class Architecture of Monitoring Log Data |
C# | Please take a look at these lines:1. in this case I type where statement directly in methodExecuted sql query is : 2. in this case I used Func for generic where clauseExecuted sql query is : as you can see , in case 2 where clause which is WHERE 1 = [ Extent1 ] . [ Id ] is missing and therefore whole records are stored... | public List < User > GetUsers ( ) { return _entity.Where ( x = > x.Id == 1 ) .ToList ( ) ; } SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Username ] AS [ Username ] , [ Extent1 ] . [ Password ] AS [ Password ] , [ Extent1 ] . [ Email ] AS [ Email ] , [ Extent2 ] . [ Id ] AS [ Id1 ] FROM [ dbo ] . [ Account_U... | Func < t , bool > vs Manually expression performance in C # lambda |
C# | I use the MS Sync Framework to sync my SQL Server instance with a local SQL CE file to make it possible working offline with my Windows app.I use GUIDs as keys . On my table I have a unique index on 2 columns : user_id and setting_id : Now I do the following : I create a new record in this table in both databases - SQL... | usersettings table -- -- -- -- -- -- -- -- -- id PK - > I also tried it without this column . Same resultuser_id FK setting_id FKvalue | Microsoft Sync Framework unique index error |
C# | This power series is valid for [ 0 , pi/2 ] and it is 10 times slower than the built in sine function in release mode . 1ms vs 10ms.But when I copy paste mysin code into the function I get practically the same time in release and my code is about 4 times faster when in debug mode.What is the deal here ? How do I make t... | const double pi = 3.1415926535897 ; static double mysin ( double x ) { return ( ( ( ( ( ( -0.000140298 * x - 0.00021075890 ) * x + 0.008703147 ) * x - 0.0003853080 ) * x - 0.16641544 ) * x - 0.00010117316 ) * x + 1.000023121 ) * x ; } static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; double a = ... | Why is my sine algorithm much slower than the default ? |
C# | I am using C # and LINQ , I have some Date in type DateAt the moment I am using this script to order a list by date of start , from the earlier to the latest.With the following code my events are not sorted : What could be wrong here ? | events.OrderBy ( x = > x.DateTimeStart ) .ToList ( ) ; return events.AsQueryable ( ) ; | How to order Dates in Linq ? |
C# | Is there a more elegant solution for adding an item to an IEnumerable than this ? Some context : | myNewIEnumerable = myIEnumerable.Concat ( Enumerable.Repeat ( item , 1 ) ) ; public void printStrings ( IEnumerable < string > myStrings ) { Console.WriteLine ( `` The beginning . `` ) ; foreach ( var s in myStrings ) Console.WriteLine ( s ) ; Console.WriteLine ( `` The end . `` ) ; } ... var result = someMethodDeliver... | Adding single item to enumerable |
C# | Suppose you have a method with the following signature : When calling this method , is there a way to specify a value for bar and not foo ? It would look something like ... ... which would translate to ... ... at compile-time . Is this possible ? | public void SomeMethod ( bool foo = false , bool bar = true ) { /* ... */ } SomeMethod ( _ , false ) ; SometMethod ( false , false ) ; | Optional Specification of some C # Optional Parameters |
C# | I have a winform code which run after a button click : Question : Why do I see one MessageBox at a time when delay=1 : But If I change delay to : 1,2,3 —I see - 3 Message Boxes without even clicking any Messagebox ? Thanks to @ Noseratio for pointing that behaviour at first place . | void button1_Click ( object sender , EventArgs e ) { AAA ( ) ; } async Task BBB ( int delay ) { await Task.Delay ( TimeSpan.FromSeconds ( delay ) ) ; MessageBox.Show ( `` hello '' ) ; } async Task AAA ( ) { var task1 = BBB ( 1 ) ; // < -- - notice delay=1 ; var task2 = BBB ( 1 ) ; // < -- - notice delay=1 ; var task3 =... | async-await 's continuations bursts — behave differently ? |
C# | I have the following example : The question is why in the second `` Equals '' call I 'm redirected to Object.Equals instead of Hello.Equals even though I 'm specifying the exact type in generic argument ? | namespace ComparisonExample { class Program { static void Main ( string [ ] args ) { var hello1 = new Hello ( ) ; var hello2 = new Hello ( ) ; // calls Hello.Equals var compareExplicitly = hello1.Equals ( hello2 ) ; // calls Object.Equals var compareWithGenerics = ObjectsEqual < Hello > ( hello1 , hello2 ) ; } private ... | Why `` Equals '' method resolution with generics differs from explicit calls |
C# | I was wondering how field pinning is expressed in .Net 's IL language , so I took a look at the example code : This generates the IL : I 'm not seeing anything here , that would explicitly tell the GC to pin the array , which instruction is actually responsible for pinning ? Also , are there other basic operations whic... | struct S { public fixed int buf [ 8 ] ; } S s = default ( S ) ; public void MyMethod ( ) { fixed ( int* ptr = s.buf ) { *ptr = 2 ; } } .method private hidebysig instance void MyMethod ( ) cil managed { // Method begins at RVA 0x2050 // Code size 25 ( 0x19 ) .maxstack 2 .locals init ( [ 0 ] int32 & pinned ) IL_0000 : ld... | How is pinning represented in IL |
C# | I was wondering what would happen if I added a list to itself . Maybe a stack overflow , maybe a compiler error ? So I executed the code and checked the local variables : The list seems to contain an infinite number of list instances . Why is there no stack overflow ? Are the lists just pointers to the original list ? ... | List < object > lstobj = new List < object > ( ) ; lstobj.Add ( lstobj ) ; | Add an object list to itself ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.