lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Uncommenting the marked line below will cause a stackoverflow , because the overload resolution is favoring the second method . But inside the loop in the second method , the code path takes the first overload.What 's going on here ?
private static void Main ( string [ ] args ) { var items = new Object [ ] { null } ; Test ( `` test '' , items ) ; Console.ReadKey ( true ) ; } public static void Test ( String name , Object val ) { Console.WriteLine ( 1 ) ; } public static void Test ( String name , Object [ ] val ) { Console.WriteLine ( 2 ) ; // Test ...
C # : Why does passing null take the overload with Object [ ] ( but only in some cases ) ?
C#
I 'm trying to access the user Id from the token but everything I try returns null . The generated token has the necessary information so I do n't think it 's the token generation.This is the part creates the tokenWhen I decode the generated token I can see all of the claims in the token but I ca n't access it on the p...
var tokenHandler = new JwtSecurityTokenHandler ( ) ; var key = Encoding.ASCII.GetBytes ( _jwtSettings.Secret ) ; var tokenDescriptor = new SecurityTokenDescriptor ( ) { Subject = new ClaimsIdentity ( new [ ] { new Claim ( JwtRegisteredClaimNames.Sub , user.Email ) , new Claim ( JwtRegisteredClaimNames.Jti , Guid.NewGui...
JWT Token Accessing AuthenticatedUser
C#
I would like to write the following methodWhere T must be a generic type that takes TItem as its generic info.Call example would be like : Edit : In my case I would only need to for collections.The actual use case is that I wanted to write a method that adds something to a ICollection sadly the ICollection does n't hav...
private void Foo < T , TItem > ( T < TItem > param1 ) private void Main ( ) { List < int > ints = new List < int > ( ) ; Foo < List , int > ( ints ) ; } private Foo < T > ( ICollection < T > )
How to make a generic method that take a generic type
C#
I am getting data from database in following way : Now , I am try to achieve this by using sql queries : But get the following error : The data reader has more than one field . Multiple fields are not valid for EDM primitive or enumeration typesIs it possible to use complex queries like above ? I use EF 6.0 .
result = ( from d in context.FTDocuments join f in context.FTDocFlags on d.ID equals f.DocID into fgrp from x in fgrp.DefaultIfEmpty ( ) where d.LevelID == levelID & & x.UserID == userID & & d.Status.Equals ( DocumentStatus.NEW ) select new Entities.Document { ArrivalDate = d.ArrivalDate.Value , BundleReference = d.Bun...
Using sql queries in EF
C#
I have the following abstract base class : And then I go ahead and implement that class : Compile ... and it works ! Is this advised or does it lead to `` evil '' code ? Is `` params '' sort of syntactic sugar ?
public abstract class HashBase { public abstract byte [ ] Hash ( byte [ ] value ) ; } public class CRC32Hash : HashBase { public override byte [ ] Hash ( params byte [ ] value ) { return SomeRandomHashCalculator.Hash ( value ) ; } }
C # params on method signature does n't break an override / implementation
C#
I have defined the following classes.Document.csDocumentOrder.csWhen serializing this to an XML I get : But I would like to have it like that , i.e . be the Document elements to be children of DocumentOrder.How can I do that ?
public class Document { // ... [ XmlAttribute ] public string Status { get ; set ; } } public class DocumentOrder { // ... [ XmlAttribute ] public string Name { get ; set ; } public List < Document > Documents { get ; set ; } } < DocumentOrder Name= '' myname '' > < Documents > < Document Status= '' new '' / > // ... <...
Serializing List < > with XmlSerializer
C#
A student of mine had a cool result which I just could n't explain.In her code , she wants to create random circles ( in WPF ) with Random colors . She made the typical beginner 's mistake of creating more than one Random generator , but bear with me , please.This is the code : This will always generate the same effect...
Random cir = new Random ( ) ; Random color = new Random ( ) ; for ( i = 0 ; i < 100 ; i++ ) { int r = cir.Next ( 0 , 50 ) ; diameter = r * 2 ; int posx = cir.Next ( 0 , ( 510 - diameter ) ) ; int posy = cir.Next ( 0 , ( 280 - diameter ) ) ; byte c1 = ( byte ) color.Next ( 255 ) ; byte c2 = ( byte ) color.Next ( 255 ) ;...
Explanation for interesting phenomenom with Random ( ) and colors
C#
How can I do it ? I followed this tutorial , so I have this method : It gives an error : Can not apply operator > = to operands of type string and string
if ( getOSInfo ( ) > = `` 7 '' ) { MessageBox.Show ( `` Your Microsoft Windows version is n't supported.\n\nPlease use Windows 7 or above to be able to use this program . `` ) ; Application.Current.Shutdown ( ) ; }
Exit if Windows version is less than 7
C#
I have a List of strings where each item is a free text describing a skill , so looks kinda like this : And I want to keep a user score for these free texts . So for now , I use conditions : Suppose In the furure I want to use a dictionary for the score mapping , such as : What would be a good way to cross between the ...
List < string > list = new List < string > { `` very good right now '' , `` pretty good '' , `` convinced me that is good '' , `` pretty medium '' , `` just medium '' ... .. } foreach ( var item in list ) { if ( item.Contains ( `` good '' ) ) { score += 2.5 ; Console.WriteLine ( `` good skill , score+= 2.5 , is now { 0...
Searching for dictionary keys contained in a string array
C#
I 'm trying to figure out a way for a derived class to be made up of members that have more specific types than those specified in the abstract base class . Here is some code that works which does what I want , but does not follow the stipulations I mention . As a result , the client code ( in Main ) must use a cast on...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Stackoverflow { class Program { static void Main ( string [ ] args ) { ConcreteFoo myFoo = new ConcreteFoo ( ) ; myFoo.BarProperty = new ConcreteBar ( ) ; ( ( ConcreteBar ) myFoo.BarProperty ) .ConcreteBarPrint ( ) ; Con...
How can one achieve the effect of overriding a base member with more specific type ?
C#
c # lets you override `` operator true '' and `` operator false '' for a class : and it sort of works . You can sayBut you ca n't sayIn every case the compiler complains.Does the c # compiler use `` operator true '' and `` operator false '' anywhere except for those very specific syntaxes ? EDITI found one more place w...
class Foo { bool Thing ; Foo ( bool thing ) { Thing = thing ; } public static bool operator true ( Foo foo ) = > foo.Thing ; public static bool operator false ( Foo foo ) = > ! foo.Thing ; } Foo foo = new Foo ( true ) ; if ( foo ) Stuff ( ) ; string s = foo ? `` yes '' : `` no '' ; Foo foo = new Foo ( true ) ; bool boo...
Does `` operator true '' in c # have exactly two places it can be used ?
C#
I 'm creating a plugin system for my application and I would like for the plugins to expose a humanly readable name . The application will show a list of available plugins , in this list the name need to be available.I want to make it very clear for the developers of the plugins what they need to do to make their plugi...
public interface IDataConsumer : IDisposable { string ConsumerName { get ; } void Consume ( DataRowSet rows ) ; ... }
Giving a plugin-class a humanly readable name
C#
I 'm having my Web Application which hosts Webservices ( svc ) which are used in a Silverlight Webapplication . After a while I added some new stuff to my Service and now I tried to refresh my proxy classes in the Silverlight Application Project.Unfortunately , Visual Studio now generates new class names.Before I had t...
public SilverlightApplication.ServiceReferenceDoc.Document Document SilverlightApplication.ServiceReferenceDoc.Document1 Document
service reference proxy class renamed
C#
I have inherited code that looks like this : Stored Procedure UpdateSomeStuffThis sp is called by ADO.NET in c # like thisI am just asking myself : Is the part IF @ @ Error > 0 Goto ERR good for anything ? If an error happens the sp would return anyway and an exception would be caught in the calling method.The calling ...
Update Table1 Set Col1=Para @ 1IF @ @ Error > 0 Goto ERRUpdate Table2 Set Col1=Para @ 2IF @ @ Error > 0 Goto ERRRETURN 0ERR : return -1 ; try { myCommand.ExecuteNonQuery ( ) ; } catch ( System.Exception ex ) { _log.Error ( ex ) ; throw ( ) ; } finally { if ( myConnection ! =null ) { myConnection.Close ( ) ; } }
TSQL performance with @ @ Error and Can they be replaced ?
C#
I need to validate values that can have one of two formats and am trying to do so with a single regular expression but ca n't figure out why it does n't work.The first format is exactly 17 alphanumeric characters and the expression ^ [ A-Za-z0-9 ] { 17 } $ correctly matches the test value 5UXWX7C56BA123456 but not the ...
var pattern1 = new Regex ( @ '' ^ ( [ A-Za-z0-9 ] { 17 } ) | ( [ A-Za-z0-9 ] { 8 } [ *_ ] [ A-Za-z0-9 ] { 2 } ) $ '' ) ; var pattern2 = new Regex ( @ '' ^ ( [ A-Za-z0-9 ] { 8 } [ *_ ] [ A-Za-z0-9 ] { 2 } ) | ( [ A-Za-z0-9 ] { 17 } ) $ '' ) ; var values = new string [ ] { `` 5UXWX7C56BA12345 '' , `` 5UXWX7C56BA123456 ''...
How to match entire string to be one of two formats with a single regular expression ?
C#
The use case that I 'm trying to solve is encapsulation of our domain models . For example , we have internal models that are utilized in a back-end processing that we do not want exposed to clients . One of the main reasons for this encapsulation is volatility of change as our domain objects may change more rapid than...
public class PublishedModel { public int Foo { get ; set ; } public string Bar { get ; set ; } } public interface IPublishedAPI { PublishedModel GetModel ( int id ) ; } public class MyApi : ApiController , IPublishedAPI { public IDomainManager _manager ; public MyApi ( IDomainManager manager ) { _manager = manager ; } ...
Is there a way to force WebAPI to strictly conform to a published interface ?
C#
I 'm just wondering why this codeboth returns 03 31 2016 instead of 03/31/2016 .
DateTime.Now.ToString ( `` MM/dd/yyyy '' ) ; and String.Format ( `` { 0 : MM/dd/yyyy } '' , DateTime.Now ) ;
String Format returns unexpected result
C#
If I do this : My result is : I 'm expecting it to beI 'm trying to replace `` t '' with `` \t '' using regex.replace . I made this example very basic to explain what I 'm trying to accomplish .
Regex.Replace ( `` unlocktheinbox.com '' , `` [ t ] '' , `` \\ $ & '' ) ; `` unlock\\theinbox.com '' `` unlock\theinbox.com ''
How do you replace a single character with a backslash using regex.replace in c #
C#
So I have this class : The code pretty much explains itself . I tried to solve that and came up with this : I havent tested it out though , but am I doing it right ? Is there better way to do that ?
class Test { private int field1 ; private int field2 ; public Test ( ) { field1 = // some code that needs field2 = // a lot of cpu time } private Test GetClone ( ) { Test clone = // what do i have to write there to get Test instance // without executing Test class ' constructor that takes // a lot of cpu time ? clone.f...
How to make clone of class instance ?
C#
I have two tables as in the snapshot below. ! [ Diagram ] [ 1 ] Scenario : A question should have only one correct answer , but can have many ( 3 in my case ) wrong answers ( like a quiz show ) .Problem : Questions table has multiple answers in the Answers table , but only one correct answer . The correct answer is the...
CREATE TABLE [ dbo ] . [ Questions ] ( [ QuestionID ] [ int ] NOT NULL , [ QuestionText ] [ nvarchar ] ( max ) NOT NULL , [ AnswerID ] [ int ] UNIQUE NOT NULL , [ ImageLocation ] [ ntext ] NULL , CONSTRAINT [ PK_Questions_1 ] PRIMARY KEY CLUSTERED CREATE TABLE [ dbo ] . [ Answers ] ( [ AnswerID ] [ int ] NOT NULL , [ A...
How to change this many to one relationship to one to one ?
C#
I have a small menu which I would like to order by the DB table id like the following : Example : The problem with my for each is that when the id changed the ordering not works.Has someone a idea how to order by parentid , previousid and next id which check every time all ids for the relationship ?
public class Obj { public string Value { get ; set ; } public int ? ParentNodeId { get ; set ; } public int ? PreviousNodeId { get ; set ; } public int ? NextNodeId { get ; set ; } } private IEnumerable < MenuNodeDTO > GetSortedMenuNodes ( int menuId ) { var nodes = LoadMenuNodes ( menuId ) ; foreach ( MenuNode menuNod...
Order menu nodes by parent , previous and next id
C#
In one of my libraries , I have code that returns a MethodInfo from an expression : I had a series of helper functions to enable calls like the following : This would enable the following syntax : This worked great , until I recently upgraded the library to .Net 4.6.1 and the latest c # compiler.In the previous version...
public MethodInfo GetMethod ( Expression expression ) { var lambdaExpression = ( LambdaExpression ) expression ; var unaryExpression = ( UnaryExpression ) lambdaExpression.Body ; var methodCallExpression = ( MethodCallExpression ) unaryExpression.Operand ; var methodInfoExpression = ( ConstantExpression ) methodCallExp...
Why do different versions of .net ( or the compiler ) generate different expression trees for the same expression
C#
I am uneasy about the way I have designed a simple program.There is a FileParser object which has OnFileOpened , OnLineParsed , and OnFileClosed events , and several objects which create smaller files based on the content of the file which the FileParser parses.The objects observing the FileParser register their method...
ParsedFileFrobber ( FileParser fileParser ) { fileParser.OnFileOpen += this.OpenNewFrobFile ; fileParser.OnLineParsed += this.WriteFrobbedLine ; fileParser.OnFileClose += this.CloseFrobFile ; } var fileParser = new FileParser ( myFilename ) ; var parsedFileFrobber = new ParsedFileFrobber ( fileParser ) ; // No further ...
Idiomatic C # for object only interacting though having registered to events
C#
I am working on a project based on WPF , C # and MVVM . Its basically a networking device configurable application via telnet.I have a following output in my wpf textbox and I want to extract MAC Address column values.I think i can not use regex because i dont have anything to match.Any help and suggestions would be gr...
active500EM # sh mac-address-tableRead mac address table ... .Vlan Mac Address Type Creator Ports -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -1 00-23-8b-87-9a-6b DYNAMIC Hardware Ethernet1/0/121 00-8c-fa-72-94-b1 DYNAMIC Hardware Ethernet1/0/11 3c-43-8e-5c-3e-05 DYNAMIC H...
How to extract matching string from large text ?
C#
I have two SQL statements in my C # code to retrieve some values . I know they are open to SQL injection since I 'm not using parameters , but I 'm not sure if I 'm implementing them correctly . ( Note : each of these are in loops that are looping through rows of a data table ) First example : In the above statement , ...
string sql2 = `` select max ( day ) as day from users u join days d on d.User_ID = u.id where u.ActiveUser = 1 and u.id = `` + Users [ `` ID '' ] .ToString ( ) ; command.CommandText = sql2 ; string dt = command.ExecuteScalar ( ) .ToString ( ) ; string sql = `` SELECT MAX ( Day ) FROM Days WHERE Project_ID IN ( SELECT I...
Properly securing SQL statement with parameters
C#
The Best practices for exceptions document on MSDN says that you can have an exception builder method inside your class if the same exception is to be used in many parts of the class . But also , it says that in some cases , it 's better to use the exception 's constructor.Let 's say I have the following code in an Use...
private MailAddress _addr ; public UserData ( string emailAddress ) { // Tries to validate the e-mail address try { _addr = new MailAddress ( emailAddress ) ; } catch { throw new ArgumentException ( nameof ( emailAddress ) , `` Invalid email address . `` ) ; } if ( _addr.Address ! = emailAddress ) { throw new ArgumentE...
Where should I create an Exception object ?
C#
I have a task which runs a loop and delays for an interval each iteration . Once the CancellationTokenSource calls Cancel ( ) I want my main code to Wait ( ) for the Task.Delay ( interval ) to finish and the task to exit the loop before my code continues . I thought this code would work but it does n't . Instead my mai...
var cts = new CancellationTokenSource ( ) ; CancellationToken ct = cts.Token ; var t = Task.Run ( ( ) = > { MyLoopTask ( 200 , ct ) ; } ) ; // Prepare informationcts.Cancel ( ) ; t.Wait ( ) ; // Send Information private async Task MyLoopTask ( int interval , CancellationToken cancelToken ) { while ( ! cancelToken.IsCan...
Why is this Task not Finishing before my code passes the Wait Command
C#
I would like to be able to create various structures with variable precision . For example : I know Microsoft deals with this by creating two structures - Point ( for integers ) and PointF ( for floating point numbers , ) but if you needed a byte-based point , or double-precision , then you 'll be required to copy a lo...
public struct Point < T > where T : INumber { public T X ; public T Y ; public static Point < T > operator + ( Point < T > p1 , Point < T > p2 ) { return new Point < T > { X = p1.X+p2.X , Y = p1.Y+p2.Y } ; } }
Are there any interfaces shared by value types representing numbers ?
C#
I have code that is building up a collection of objects . I 'm trying to reduce the number of .ToList ( ) calls I make , so I 'm trying to keep it as IEnumerable < T > for as long as possible.I have it almost finished except for two properties which need to be set to a value which is passed into the calling method : If...
private IEnumerable < X > BuildCollection ( int setMe ) { IEnumerable < Y > fromService = CallService ( ) ; IEnumerable < X > mapped = Map ( fromService ) ; IEnumerable < X > filteredBySomething = FilterBySomething ( mapped ) ; IEnumerable < X > sorted = filteredBySomething .OrderBy ( x= > x.Property1 ) .ThenBy ( x= > ...
Any way to project `` original plus a few changes '' with a LINQ query ?
C#
I 'm trying to join two different class models in an MVC project together so I can order them ascending/descending . I 've tried several permutations but ca n't seem to get the LINQ query to play nice . Any suggestions on what I 'm doing wrong ? I 'm a beginner when it comes to this , but if I 'm understanding this cor...
var lateContact = from c in JPLatestContact join s in JPStudent on c.ApplicationUserId equals s.ApplicationUserId orderby c.JPLatestContactDate ascending select s ;
LINQ Join Query Structure Resulting in CS0119 Error
C#
I 'm trying to mock a third-party interface that I 'm using ( EventStore ClientAPI/IEventStoreConnection ) , in particular this method : The problem I 'm having is that the return type StreamEventsSlice has readonly fields and an internal constructor i.e.In my test code I 'm mocking the event store connection using Moq...
Task < StreamEventsSlice > ReadStreamEventsForwardAsync ( string stream , long start , int count , bool resolveLinkTos , UserCredentials userCredentials = null ) ; public class StreamEventsSlice { public readonly string Stream ; //other similar fields internal StreamEventsSlice ( string stream ) //missing other fields ...
Mock third-party interface with return type that has readonly props & internal ctor
C#
I am having some problems with a quite easy task - i feel like im missing something very obvious here.I have a .csv file which is semicolon seperated . In this file are several numbers that contain dots like `` 1.300 '' but there are also dates included like `` 2015.12.01 '' . The task is to find and delete all dots bu...
2015.12.01 ; 13.100 ; 500 ; 1.200 ; 100 ; 2015.12.01 ; 13100 ; 500 ; 1200 ; 100 ;
Delete character out of string
C#
Linq to objects works on any IEnumerable object . The variablesandare both IEnumerable < string > , but if I want to know how many items each one of them has , I can use Length property on the array and Count property on the list . Or I can use the Count method from Linq , which will work for both.The question is : doe...
string [ ] foo = new string [ ] { } ; var bar = new List < string > ( ) ; if ( obj is Array < T > ) DoSomethingForArray ( obj as Array < T > ) ; else if ( obj is List < T > ) DoSomethingForList ( obj as List < T > ) ; else if ( obj is Collection < T > ) DoSomethingForCollection ( obj as Collection < T > ) ; else DoSome...
Does Linq optimizes execution based on real collection type ?
C#
Why does this code prints False ? Do I understand correctly that when compared , they are compared not as strings , but as objects , which is why not their values are compared , but the addresses to which they point ?
class Program { public static void OpTest < T > ( T s , T t ) where T : class { Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` string '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( s1 ) ; string s2 = sb.ToString ( ) ; OpTest ( s1 , s2 ) ; } }
Comparison of Generics in C #
C#
I am trying to save data using soap Jquery with C # WebMethod But can not save data in SQL Server please help me how can I save data using Soap jquery.I am using IDE Visual Studio 2015 .
< script type= '' text/javascript '' > function SavePersonRecord ( ) { var Name = $ .trim ( $ ( ' # < % =txtName.ClientID % > ' ) .val ( ) ) ; var LName = $ .trim ( $ ( ' # < % =txtlname.ClientID % > ' ) .val ( ) ) ; var Company = $ .trim ( $ ( ' # < % =txtCompany.ClientID % > ' ) .val ( ) ) ; var Messege = `` '' ; if ...
How Can I save Data using Soap Jquery in SQL Server 2012 ?
C#
Given the following code : the results are as in the comments - both lines print 666.I 'd expect Console.WriteLine ( new B ( ) ) ; to write 667 , while there is a double overload of Console.WriteLine.Why is that happening ?
using System ; namespace Test721 { class MainClass { public static void Main ( string [ ] args ) { Console.WriteLine ( new A ( ) ) ; //prints 666 Console.WriteLine ( new B ( ) ) ; //prints 666 Console.ReadLine ( ) ; } } public class A { public static implicit operator int ( A a ) { return 666 ; } } public class B : A {...
Conversion rules for overloaded conversion operators
C#
I am initialising and array from items in a list as follows : I have a secondary List that i would like to add to the same array inline in the initialiser , something like this ( ) : Is this possible or will i have to combine everything before the initial select statement ?
MyArray [ ] Arrayitems = SomeOtherList.Select ( x = > new MyArray [ ] { ArrayPar1 = x.ListPar1 , } ) .ToArray ( ) MyArray [ ] Arrayitems = SomeOtherList .Select ( x = > new MyArray [ ] { ArrayPar1 = x.ListPar1 , } ) .ToArray ( ) .Join ( MyArray [ ] Arrayitems = SomeOtherListNo2 .Select ( x = > new MyArray [ ] { ArrayPa...
Combing Array Inline - LINQ
C#
I have a C # .NET classes that exist outside of a namespace that need to be accessed inside of IronPython . Typically I would do : However , I do not have a namespace .
import SomeNamespacefrom SomeNamespace import *
How do I import non namespaced types into IronPython ?
C#
I just can not understand why s3 interned , but ReferenceEquals was False . Dose they have two copies in intern pool ? Thanks in advance .
string s1 = `` abc '' ; string s2 = `` ab '' ; string s3 = s2 + `` c '' ; Console.WriteLine ( string.IsInterned ( s3 ) ) ; // abcConsole.WriteLine ( String.ReferenceEquals ( s1 , s3 ) ) ; // False
Why string interned but has different references ?
C#
I have a class like this : And I have to make a search by the value received from the user , it could be , any attribute of this class . I have this too : I have four methods like this , the only difference is the attribute . Please , can anybody tell me how can I do this in just one method or is n't possible ? Thanks ...
class Person { private String sName ; private String sPhone ; private String sAge ; private String sE_Mail ; // … code … } public IEnumerable < Person > SearchByPhone ( string value ) { return from person in personCollection where person . **SPhone** == value select person ; }
Linq search by differents values
C#
String object behaves like a Value type when using == and ! = operators which means the actual object rather than the reference is checked.What about parameter passing , assignments and copying ? String Parameter Passing : When a reference type is passed to a method , its reference is copied but the underlying object s...
public static void main ( ) { string messageVar = `` C # '' ; Test ( messageVar ) ; // what about in assignement ? string messageVar2 = messageVar ; } public void Test ( string messageParam ) { // logic }
How a String type get Passed to a Method or Assigned to a Variable in C # ?
C#
I 'm trying to create some expression at runtime to change a given dictionary 's values . I created this snippet which generates the expression successfully and compiles it an Action . But calling the action can not modify dictionary 's value , and also does n't throw any error . Here is the code : As you can see , it ...
public class ChangeDicValue { public void Change ( IDictionary < string , object > dic ) { var blocks = MakeCleaningBlock ( dic ) ; foreach ( var block in blocks ) block.Invoke ( dic ) ; } private List < Action < IDictionary < string , Object > > > MakeCleaningBlock ( IDictionary < string , object > dic ) { var allKeys...
Runtime generated expression can not change dictionary 's values
C#
I am new to C # and I am trying to print out a number from a different namespace in my main . I will provide the code below.I want to have the x from Program2 class appear in my main which is in Program Class .
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 ) { Console.WriteLine ( `` hello world '' + x ) ; Console.ReadLine ( ) ; } } } namespace Applicaton { class Program2...
How does connecting Namespaces work in C # ?
C#
I am newbie to C # and I 'm doing some easy practices in VS code.I have an array of colors and a method that returns the corresponding index of the inputted color ( Resistor Color exercise ) .I want to see the result of the program when I run the program in the terminal , but nothing shows ! For example , when I choose...
using System ; public class ResistorColor { private void Main ( string [ ] args ) { int a = ColorCode ( `` brown '' ) ; Console.WriteLine ( a.ToString ( ) ) ; } public static string [ ] colors = { `` black '' , `` brown '' , `` red '' , `` orange '' , `` yellow '' , `` green '' , `` blue '' , `` violet '' , `` grey '' ...
Why I can not see the output of the program I wrote in C # in VS Code when I run it in the terminal
C#
I Have following problem : is it possible to do it ?
class Request < T > { private T sw ; public Request ( ) { //How can i create here the instance like sw = new T ( ) ; } }
How to set/create a Generics instance ?
C#
Is it good approach in the model binder use the code like this : And then `` format '' is a variable with different ( customer specific ) date format . Like 12/31/2013 or 31.12.2013 or other ones.I have big problem with the format binding because if user puts the date with only 1 digit like : 1/1/2014 it will not parse...
TryParseDate ( result.AttemptedValue , format , out parsedDate )
What is the best way to parse dates in binder
C#
I have an application has a collection of domain objects that need to be updated in real-time . Several threads can take action that modify the items in this collection and must do so safely . The current approach is rather simplistic , taking essentially a global lock before making any changes . More or less something...
private readonly object lockObject = new object ( ) ; private Dictionary < int , Widget > items ; private void UpdateAllWidgets ( ) { lock ( this.lockObject ) { // Update all the widgets . No widgets should be permitted to be // updated while this is running . } } private void UpdateWidget ( int widgetId ) { lock ( thi...
How do I efficiently support both item- and collection-level locking ?
C#
UPDATEthanks to @ usr I have got this down to ~3 seconds simply by changingtoI have a database with two tables - Logs and Collectors - which I am using Entity Framework to read . There are 86 collector records and each one has 50000+ corresponding Log records . I want to get the most recent log record for each collecto...
.Select ( log = > log.OrderByDescending ( d = > d.DateTimeUTC ) .FirstOrDefault ( ) ) .Select ( log = > log.OrderByDescending ( d = > d.Id ) .FirstOrDefault ( ) ) SELECT CollectorLogModels_1.Status , CollectorLogModels_1.NumericValue , CollectorLogModels_1.StringValue , CollectorLogModels_1.DateTimeUTC , CollectorSetti...
How can i improve the performance of this LINQ ?
C#
I have a winforms project which depends on a custom library . Everything with the app is working fine except a problem I can not pin down . Basically I have a form which is created from another form which displays it as a dialog : This dialog form populates a dropdown list from the SqlServer using the below function wh...
DataItems.ImportForm frmImportTextDelimited = new DataItems.ImportForm ( ) ; frmImportTextDelimited.ShowDialog ( ) ; public class AuthorityTypeSearcher { public List < IntValuePair > GetAllAuthorityTypes ( ) { List < IntValuePair > returnList = new List < IntValuePair > ( ) ; using ( var conn = new SqlConnection ( Glob...
Break in dubugger not `` working '' .. code execution continues
C#
Output of the following code : isIsZeroA : False , IsZeroB : TrueStrangely , when I put a breakpoint after if ( count == 323 ) while debugging and put expression ( a * 0.1 ) == 0 in Visual Studio Watch window , it reports that expression is true.Does anyone know why expression a * 0.1 is not zero , but when assigned to...
var a = 0.1 ; var count = 1 ; while ( a > 0 ) { if ( count == 323 ) { var isZeroA = ( a * 0.1 ) == 0 ; var b = a * 0.1 ; var isZeroB = b == 0 ; Console.WriteLine ( `` IsZeroA : { 0 } , IsZeroB : { 1 } '' , isZeroA , isZeroB ) ; } a *= 0.1 ; ++count ; }
Why storing a value in a variable changes the outcome of equality comparison ?
C#
That might not be the best way to phrase it , but I 'm considering writing a tool that converts identifiers separated by spaces in my code to camel case . A quick example : I was wondering if writing a tool like this would run into any ambiguities assuming it ignores all keywords . The only reason I can think of is if ...
var zoo animals = GetZooAnimals ( ) ; // i ca n't help but type thisvar zooAnimals = GetZooAnimals ( ) ; // i want it to rewrite it like this
Is there a syntactically legal expression that has 2 consecutive identifiers separated only by white space in C # ?
C#
This code works : This code does not compile : CS1061 'int ? ' does not contain a definition for 'Parse ' and no extension method 'Parse ' accepting a first argument of type 'int ? ' could be found ( are you missing a using directive or an assembly reference ? ) My example may look silly , but it makes a lot more sense...
class Example { public Int32 Int32 { get { return Int32.Parse ( `` 3 '' ) ; } } } class Example { public Int32 ? Int32 { get { return Int32.Parse ( `` 3 '' ) ; } } } public Choice ? Choice { get { return Choice.One ; } }
Why does making this getter nullable cause a compile error ?
C#
I am using code quality tools and they are saying that I can have a null deference on line 3 in the following block style : It sugests making the following change : How does this change the potential for a null deference exception ? According to msdn is will return true if `` provided expression is non-null , and the p...
1 if ( var1 is Type1 ) 2 { 3 ( var1 as Type1 ) .methodCall ( ) ; 4 } 1 Type1 tempVar = var1 as Type1 ; 2 if ( tempVar ! = null ) 3 { 4 tempVar.methodCall ( ) ; 5 }
Can the result of as operator be null if the is operator returns true ?
C#
Here 's the code : The result is $ 11000.I 'd like to have 01000 from 00000.But , I guess , $ 1 is confused with $ 11 .
string myVar = `` 00000 '' ; string myPtrn = `` ( . ) . ( ... ) '' ; string mySub = `` $ 1 '' + `` 1 '' + `` $ 2 '' ; string myResult = Regex.Replace ( myVar , myPtrn , mySub ) ; MessageBox.Show ( `` Before : \t '' + myVar + `` \nAfter : \t '' + myResult ) ;
Substitution number confusing
C#
This is really puzzling me . I know LINQ-to-SQL handles selects by processing the expression tree and attempting to translate stuff via the generated query , which is why some function translations do n't work property ( string.IsNullOrWhitespace is a regular annoyance ) .I hit a situation in my code where LINQ-to-SQL ...
// # define BREAK_THE_CODEusing System ; using Sandbox.Data ; using System.Collections.Generic ; using System.Linq ; namespace Sandbox.Console { class Program { static void Main ( string [ ] args ) { using ( var dataContext = new SandboxDataContext ( ) ) { List < MyValue > myValueList ; try { myValueList = dataContext....
Why does LINQ-to-SQL sometimes allow me to project using a function , but sometimes it does not ?
C#
Yesterday , after running Visual Studio code analysis on our codebase , the following code was highlighted as an issue : The warning that was returned was Warning CA2202 Object 'stringReader ' can be disposed more than once in method ' ( method name ) ' . To avoid generating a System.ObjectDisposedException you should ...
using ( var stringReader = new StringReader ( someString ) ) { using ( var reader = XmlReader.Create ( stringReader ) ) { // Code } }
What is the resulting behavior when an IDisposable is passed into a parent IDisposable
C#
I understand that in .NET , finalizers are run even if an object is partially constructed ( e.g . if an exception is thrown out of its constructor ) , but what about when the constructor was never run at all ? BackgroundI have some C++/CLI code that does effectively the following ( I do n't believe this is C++/CLI spec...
try { ClassA ^objA = FunctionThatReturnsAClassA ( ) ; ClassB ^objB = gcnew ClassB ( objA ) ; // ClassB is written in C # in a referenced project ... } catch ( ... ) { ... }
In .NET , can a finalizer be run even if an object 's constructor never ran ?
C#
I am trying to implement a command pattern with strongly typed input and output parameters for the command itself . First of all I have created two interfaces that marks the input and the output for the command : Then I have created the base classes and interfaces . This is the abstract receiver and this the abstract c...
interface IRequest { } interface IResponse { } interface IReceiver < TRequest , TResponse > where TRequest : IRequest where TResponse : IResponse { TResponse Action ( TRequest request ) ; } abstract class AbstractCommand < TRequest , TResponse > where TRequest : IRequest where TResponse : IResponse { protected IReceive...
Type error in command pattern
C#
I just learned that having a generic argument as the type of an out parameter forces that generic type to be invariant . This is surprising to me . I thought out parameters are treated the same as return types ( i.e . if the generic parameter is covariant , then it can be used in as an out out parameter ) , since they ...
public class Program { public static void Main ( ) { // can not convert from 'out object ' to 'out string ' F ( out object s ) ; // passing an out object } public static void F ( out string o ) { o = null ; } } // This is the semantically equivalent version of the above , just without `` out '' public class Program { p...
Why ca n't I convert from 'out BaseClass ' to 'out DerivedClass ' ?
C#
Given this class : This code snippet does n't compile : error CS0266 : Can not implicitly convert type 'System.Collections.Generic.IEnumerable < int > ' to 'Spikes.Implicit.Wrapper < System.Collections.Generic.IEnumerable < int > > ' . An explicit conversion exists ( are you missing a cast ? ) But the compiler is perfe...
public class Wrapper < T > { public Wrapper ( T value ) { Value = value ; } public T Value { get ; } public static implicit operator Wrapper < T > ( T value ) { return new Wrapper < T > ( value ) ; } } IEnumerable < int > value = new [ ] { 1 , 2 , 3 } ; Wrapper < IEnumerable < int > > wrapper = value ; Wrapper < IEnume...
Unable to implicitly 'wrap ' an IEnumerable
C#
I get objects byHow can I get a List of the objects with a type given by a string ?
IEnumerable < ObjectStateEntry > om = context.ObjectStateManager.GetObjectStateEntries ( System.Data.EntityState.Modified ) ; Type typ = Type.GetType ( `` mytype '' ) ; var om2 = om.Select ( s = > s.Entity ) .OfType < typ > ( ) ; // does not work
Getting List of Objects by a type given by a string
C#
I have a buffer of type ReadOnlySequence < byte > . I want to extract a subsequence ( which will contain 0 - n messages ) from it by knowing that each message ends with 0x1c , 0x0d ( as described here ) .I know the buffer has an extension method PositionOf but itReturns the position of the first occurrence of item in t...
private SequencePosition ? GetLastPosition ( ReadOnlySequence < byte > buffer ) { // Do not modify the real buffer ReadOnlySequence < byte > temporaryBuffer = buffer ; SequencePosition ? lastPosition = null ; do { /* Find the first occurence of the delimiters in the buffer This only takes a byte , what to do with the d...
Is there something like Buffer.LastPositionOf ? Find last occurence of character in buffer ?
C#
I 'm puzzled with a problem regarding C # List , the code below throws ArgumentOutOfRangeException : As far as I understand the code above , the method will apply the lambda from the element 0 until it reaches 5 elements ( element 4 ) , but it throws the ArgumentOutOfRangeException even if it must n't according to my u...
List < int > l = new List < int > ( ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; l.Add ( 1 ) ; // 15 elements// v < -- - From 0l.FindLastIndex ( 0 , 5 , v = > v ! = ...
FindLastIndex ArgumentOutOfRangeException when parameter count is less than List.Count
C#
I have a scenario where I need to join two tables : ABI need to use LINQ 's query syntax to join these two tables.The left table needs to be Table A.Though I need to join based on whether the `` text '' column contains the text from the Name column in Table A.The code should look something like this : I ca n't seem to ...
| -- -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- || ID | Name || -- -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- || 1 | John || -- -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- || 2 | Matt || -- -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -- -- || 3 | Emma || -- -- -- -- -- --...
Join in LINQ Query Syntax : moving right side to the left
C#
If I have a class as below : But construct it using the same types ( new MyClass < int , int > ( ) ) This compiles fine , but if I try to call DoSomething it errors because of an ambiguous call , which of course is correct . But what if the method was called through reflection or some other dynamic way . I guess it wou...
class MyClass < T , U > { public void DoSomething ( T t ) { } public void DoSomething ( U u ) { } }
2 methods using 2 generics of same type
C#
I 'm querying a collection using linq and grouping my data by datetime property using the following code : Everything is good , when use an anonymous type . But If I define my own classand modify my query accordinglythen grouping is not working and I 'm getting a plain list of the objects . Why ?
var querty = from post in ds.Appointments group post by new { Year = post.DateOfVisit.Year , Month = post.DateOfVisit.Month } ; class YearMonth { public int Year ; public string Month ; public YearMonth ( int year , int month ) { Year = year ; Month = month ; } public override string ToString ( ) { return string.Format...
Using strict types in linq grouping query
C#
In an effort to learn more about Func Delegates and Expression trees , I put together a simple example , however I am not getting the results I expect . Below is my code that has a Func that expects a Params class and a List of Products . The idea is to apply the Params Class as a filter against a list of Products . As...
static void Main ( string [ ] args ) { Products products = CreateProducts ( ) ; Params param = new Params { Val = `` ABC '' } ; Func < Params , Products , IEnumerable < Product > > filterFunc = ( p , r ) = > r.Where ( x = > x.Sku == p.Val ) .AsEnumerable ( ) ; Products prods = filterFunc ( param , products ) .ToList ( ...
Returning values with a Func Delegate
C#
I have been reading about an implementation of the diamond-square algorithm in C # that wraps around to create seamless textures . To calculate the next point , an average is taken of four sample points arranged in a square or a diamond . If a sample point lies of the edge of the texture , it is wrapped around to the o...
public double sample ( int x , int y ) { return values [ ( x & ( width - 1 ) ) + ( y & ( height - 1 ) ) * width ] ; }
What is the function of bitwise & in this statement ?
C#
Access base class A function by derived class B object in c # Is there is any way i can access function ( Sum ) of A class By B class object and get output 10. ?
Class A { public int Sum ( int i ) { return i+3 ; } } Class B : A { public int Sum ( int i ) { return i+4 ; } } B objectB=new B ( ) ; int result=objectB.Sum ( 7 ) ; output:11
Access base class A function by drived class B object in c #
C#
I just have a function here that caller wants number of bytes and then it returns the bytes but if there are not enough bytes in file it should return an smaller array . is there better approach to do this ? I mean not getting 2 array and use BlockCopy ?
byte [ ] GetPartialPackage ( string filePath , long offset , int count ) { using ( var reader = new FileStream ( filePath , FileMode.Open , FileAccess.Read , FileShare.Read ) ) { reader.Seek ( offset , SeekOrigin.Begin ) ; byte [ ] tempData = new byte [ count ] ; int num = reader.Read ( tempData , 0 , count ) ; byte [ ...
How to obtain a better approach in reading file ?
C#
I have a enum in my C # code and i want to get names from enum in my jQuery validate rules . Enum : Validate : This really works , but I want make something like this : In C # I can get names in this way : How can I make it in javascript ? Thanks for advice !
public enum EnumItemField { Zero = 0 , One = 1 , Two = 2 , Three = 3 , Four = 4 , Five = 5 , } function updateFieldStatus ( ) { } $ ( document ) .ready ( function ( ) { $ ( `` # IntegrationService '' ) .validate ( { rules : { //Set range of Start `` config.EnumFormat [ Zero ] .Start '' : { required : true , digits : tr...
How to use a C # enumeration in Javascript
C#
I have the following code that is executed by Hangfire ( there is no HttpContext ) and works perfectly when I run it locally : The way we have our application set up however is as follows : https : //application.net < - One applicationhttps : //application.net/admin < - The other application that this code runs on.When...
class FakeController : ControllerBase { protected override void ExecuteCore ( ) { } public static string RenderViewToString ( string controllerName , string viewName , object viewData ) { using ( var writer = new StringWriter ( ) ) { var routeData = new RouteData ( ) ; routeData.Values.Add ( `` controller '' , controll...
Getting MVC5 Views as string , with nested hosting
C#
I have the following code that creates 10 threads which in turn write out messages to the console : My understanding is that ParameterizedThreadStart takes an object for which a copy of the reference is sent to the thread . If that is the case since I have not made a local copy of i within each loop all new threads wou...
for ( int i = 0 ; i < 10 ; i++ ) { { Thread thread = new Thread ( ( threadNumber ) = > { for ( int j = 0 ; j < 10 ; j++ ) { Thread.Sleep ( 200 ) ; Console.WriteLine ( string.Format ( `` Thread : { 0 } , Line : { 1 } '' , threadNumber , j ) ) ; } } ) ; thread.Start ( i ) ; } }
Captured variables in ParameterizedThreadStart
C#
I have an page and in my Send event , I need pass as a parameter an value `` Name '' .But this name have accentuation and , in example for name `` Raúl Lozada '' sends `` Ra & # 250 ; l Lozada '' to my procedure parameter.How I can correct it ? In my HTML page , it loads correctly !
< asp : BoundField DataField= '' User '' HeaderText= '' User '' / > SqlParameter myParam4 = oCommand.Parameters.Add ( `` @ User '' , SqlDbType.NChar ) ; myParam4.Value = row.Cells [ 0 ] .Text ;
Send parameter with accentuation c #
C#
VS2010 / R # 5.1I have this `` line '' of code : I perform a R # code cleanup , which changes the code as follows : That is , it reformats the statement such that it appears entirely on one line.What IDE/R # setting is responsible for this ? What can I change to preserve my line breaks when I perform a R # code cleanup...
With.Mocks ( _mocks ) .Expecting ( ( ) = > { _fooServiceMock.Expect ( x = > x.FooMethod ( ) ) .Return ( fooMockData ) ; } ) .Verify ( ( ) = > { } ) ; With.Mocks ( _mocks ) .Expecting ( ( ) = > { _fooServiceMock.Expect ( x = > x.FooMethod ( ) ) .Return ( fooMockData ) ; } ) .Verify ( ( ) = > { } ) ;
What R # setting is reformatting this line ?
C#
Is it possible to check the type of a generic type , without using any generic parameters ? For example , I would like to be able to do something similar to the following ( actual types ' names have been changed to protect the innocent ) : The above code currently generates the following error : Is there a way around t...
var list = new List < SomeType > ( ) ; ... if ( list is List ) { Console.WriteLine ( `` That is a generic list ! `` ) ; } Using the generic type 'System.Collections.Generic.List < T > ' requires 1 type arguments
How can I determine the parameterless-type of a C # generic type for checking purposes ?
C#
I have a set of objects that themselves contain a set.Here 's some test data : I want to use OrderBy in Linq so that : Smith and Jones are ordered together because they fly the same planesHiggins and Wilson are ordered together because they fly the same planesdoes n't matter whether Higgins+Wilson end up before or afte...
private class Pilot { public string Name ; public HashSet < string > Skills ; } public void TestSetComparison ( ) { var pilots = new [ ] { new Pilot { Name = `` Smith '' , Skills = new HashSet < string > ( new [ ] { `` B-52 '' , `` F-14 '' } ) } , new Pilot { Name = `` Higgins '' , Skills = new HashSet < string > ( new...
Linq OrderBy to group objects with the same sets
C#
C # 6 introduced string interpolation and a shorter way to specify the format string . Why the two last lines output a different result ? Am I missing something ? Try it with DotnetFiddleAs a side note here is the source code of IntPtr ToString ( ) in dotnet core :
IntPtr ptr = new IntPtr ( 0xff ) ; Console.WriteLine ( ptr.ToString ( ) ) ; // 255Console.WriteLine ( ptr.ToString ( `` x '' ) ) ; // ffConsole.WriteLine ( $ '' 0x { ptr.ToString ( `` x '' ) } '' ) ; // 0xffConsole.WriteLine ( $ '' 0x { ptr : x } '' ) ; //0x255 public unsafe String ToString ( String format ) { # if WIN...
C # 6 String interpolation + short format string bug ?
C#
By default , StringWriter will advertise itself as being in UTF-16 . Usually XML is in UTF-8.So I can fix this by subclassing StringWriterBut why should I worry about that ? What will be if I decide to use StringWriter ( like I did ) instead of Utf8StringWriter ? Will I have some bug ? After that I will write this stri...
public string Serialize ( BackgroundJobInfo info ) { var stringBuilder = new StringBuilder ( ) ; using ( var stringWriter = new StringWriter ( stringBuilder , CultureInfo.InvariantCulture ) ) { var writer = XmlWriter.Create ( stringWriter ) ; ... public class Utf8StringWriter : StringWriter { public override Encoding E...
Should I be worried about encoding during serialization ?
C#
I have a ViewBag.List > where i have competition , and every competition has a list of teams.Example : List of { Premier League : [ Arsenal , Chelsea etc ] Bundesliga : [ Bayern Munchen , Wolfsburg etc ] I have 2 selects . When the user selects the first select ( competition ) , i want that the second select will have ...
function myFunction ( select ) { var sel = document.getElementById ( `` teams '' ) ; if ( select.value == 'Premier League ' ) { sel.innerHTML = `` '' ; @ foreach ( var team in ViewBag.List [ 0 ] ) // Premier League { @ : var x = document.createElement ( `` OPTION '' ) ; @ : x.setAttribute ( `` value '' , @ team ) ; @ :...
< select > for < select > c # to javascript
C#
Suppose I got a parent class and a child class : As of current , both GetParentName ( ) and GetChildName ( ) will return Child.However , in my scenario , I 'd like to get the name of the class in which the method is declared.Thus GetChildName ( ) should return Child but GetParentName ( ) should return Parent.Is this by...
public abstract class Parent { public string GetParentName ( ) { return GetType ( ) .Name ; } } public class Child : Parent { public string GetChildName ( ) { return GetType ( ) .Name ; } }
Getting the name of the declaring class ?
C#
I have managed to open my EA project via the automation API , but do n't know the right format in which to pass the arguments to the ImportDirectory ( … ) method : When doing the import manually I select the following options in EA 's Import Source Directory window : C # as programming languagerecursively process subdi...
var repo = new EA.RepositoryClass ( ) ; repo.OpenFile ( `` some.eap '' ) ; var proj = repo.GetProjectInterface ( ) ; string language = `` ... '' ; // what to put here for C # ? string extraoptions = `` ... '' ; // what to put here for my option ( see below ) proj.ImportDirectory ( `` { C5007706-B7DA-4ACC-9123-F934F9B60...
In which format do I have to pass arguments to Project.ImportDirectory ( … ) ?
C#
I get a json string from an external web service . I would like to save the events from the events array in my database . How can I get List < FacebookEvents > ? My current attempt does n't work : List < FacebookEvents > my_obj = JsonConvert.DeserializeObject < FacebookEvents > ( jsonString ) ; Source json :
{ `` events '' : [ { `` id '' : `` 163958810691757 '' , `` name '' : `` 3Bridge Records presents inTRANSIT w/ David Kiss , Deep Woods , Eric Shans '' , `` coverPicture '' : `` https : //scontent.xx.fbcdn.net/t31.0-8/s720x720/13679859_10153862492796325_8533542782240254857_o.jpg '' , `` profilePicture '' : `` https : //s...
Parse json string with JsonConvert c #
C#
Assuming that I have the following three methodshow can I pass the functions Function1 and Function2 with designated parameters to the Execute method ? e.g . like thisbut above example is calling the function , I want it to be called only in the Execute method.I hope it got clear , if it does n't , I am looking for a w...
void Execute ( < What to put here ? > method ) { method ( ) ; } void Function1 ( string a ) { ... } void Function2 ( int a ) { ... } Execute ( Function1 ( `` Foo '' ) ) ; void Execute ( Action method ) { method ( ) ; } void Function3 ( ) { ... } Execute ( Function3 ) ;
Pass any function regardless of its parameters
C#
Every so often ( e.g . NUnit 's TestCaseData ) , I see an object that has one or several constructors as follows : If an object has the params constructor , though , what is the advantage of defining the previous ones ?
MyObject ( object arg ) MyObject ( object arg1 , object arg2 ) MyObject ( object arg1 , object arg2 , object arg3 ) //guess they got tired of writing constructors ? MyObject ( params object [ ] args )
Why have both params and muti-object constructors ?
C#
I want to use DbContext in multiple threads , but the underlying database has a problem if two threads are writing at the same time.So I am using lockObject to prevent two SaveChanges ( ) at the same time.That works fine in SaveChanges ( ) , but I do n't know how to do the same in SaveChangesAsync ( ) .I think the solu...
public class MyDbContext : DbContext { ... . static readonly object lockObject = new object ( ) ; public override int SaveChanges ( ) { lock ( lockObject ) return base.SaveChanges ( ) ; } public override Task < int > SaveChangesAsync ( CancellationToken cancellationToken = default ) { lock ( lockObject ) return base.Sa...
Locking async task c #
C#
I am currently doing some tests on F # maps vs C # dictionaries . I realize they are quite different implementation wise but they do fill the same sort of use for their respective languages.I have designed a simple test to check the insertion times due to the F # map being immutable thus it has to create an entirely ne...
//F # module Test = let testMapInsert ( ) = let sw = Stopwatch ( ) let rec fillMap endIdx curr map = if curr = endIdx then map else fillMap endIdx ( curr + 1 ) ( map | > Map.add curr curr ) sw.Start ( ) let q = fillMap 100000000 Map.empty sw.Stop ( ) printfn `` % A '' sw.ElapsedMilliseconds //C # class Program { static...
Increase F # map insertion performance
C#
I have a panel with buttons . my buttons are create dynamically . I want to have 4 rows with 4 buttons each . but I only get one row.Desired result :
foreach ( CategoriesDataSet.CategoriesRow category in DataRepository.Categories.Categories ) { if ( ! category.CategoryName.Equals ( `` ROOT '' ) ) { SimpleButton button = new SimpleButton ( ) ; button.Text = category.CategoryName ; button.Tag = category.CategoryId ; button.Size = new Size ( 82 , 70 ) ; if ( lastButton...
Controller wrapping in panel
C#
I 'm trying to skip duplicates for the list of values below . The result I 'm trying to achieve is -112.94487230674 , -49.47838592529 , -89.9999574979198 , I 'm using the HashSet class . I 've implemented the IEqualityComparer below but it 's not working.What am I doing wrong ? Here is the list of values :
class HeightEqualityComparer : IEqualityComparer < double > { public bool Equals ( double a , double b ) { return a - b < 1e-3 ; } public int GetHashCode ( double value ) { return value.GetHashCode ( ) ; } } [ 0 ] -112.94487230674 double [ 1 ] -112.94487230674001 double [ 2 ] -49.478385925290006 double [ 3 ] -49.478385...
Avoid duplicates in HashSet < double > for slightly different values
C#
I have a ( hopefully ) simple question : I have some classes : I have two dictionaries : And I have a method : and a method call : but now I get the error that I ca n't convert Dictionary < int , Foo1 > to Dictionary < int , Foo > .How do I solve this problem ? Thank you : )
class Fooclass Foo1 : Fooclass Foo2 : Foo Dictionary < int , Foo1 > dic1 Dictionary < int , Foo2 > dic2 private static int Method ( Dictionary < int , Foo > ) Method ( dic1 ) ;
Dictionary - inherited classes
C#
I have a list of objects with structure Sample data : My other list of objects is with structureSample data : I wish to change the second list to the first list structure and then do a union all ( concat ) with first list.So result ought to look as below : All help is sincerely appreciated..Thanks
string source , string target , int count sourcea targeta 10sourcea targetb 15sourcea targetc 20 string source , int addnvalueacount , int addnvaluebcount , int addnvalueccount sourcea 10 25 35 sourcea targeta 10sourcea targetb 15sourcea targetc 20sourcea addnlvaluea 10sourcea addnlvalueb 25sourcea addnlvaluec 35
merging two lists with diff structures C #
C#
I 'm beginner in the usage of threads and in the examples that I 've seen ( as here and here ) a new thread must be assigned to a method . But , is there a way of making that inside the method ? I 'm looking for something like this : Thank you .
public void MyMethod ( ) { //Start new thread that affects only this method//Do stuff//More stuff }
Start in a new thread in the same method
C#
Suppose we write a system for tests . Test contains the list of tasks and each task contains question and the list of answers . Also we assume that question or answer can be not only the text , but image for example . So we use generics : And the problem occurs when we creating the Task : How to write that TQuestion sh...
public interface IQuestion < T > { T Content { get ; } } public interface IAnswer < T > { T Content { get ; } bool IsCorrect { get ; } } interface ITask < TQuestion , TAnswer > { TQuestion Question { get ; } List < TAnswer > Answers { get ; } } interface ITask < TQuestion , TAnswer > where TQuestion : IQuestion < objec...
Using where constraints with generic interface or class
C#
Fairly basic question , imagineDo both a and b take up the same space in memory ? I assume b is larger than a as it has to store the length of itself somewhere , so I thought it would be IntPtr.Size larger , but I am not sure . I am trying to write code where the length of the array is determined at runtime , and can b...
int a = 5 ; int [ ] b = new int [ 1 ] ; b [ 0 ] = 5 ;
Is an array of length 1 the same size as a single variable of the same type ?
C#
I have code like this : Works great but if row [ `` Forename '' ] is null in the database , it is actually DBNull here and it ca n't cast DBNull to a string , or perform the comparison between DBNull and string . Some values are also nullable < int > , and it ca n't compare DBNull with int ? Is there a helper method to...
foreach ( DataRow row in dataTable.Rows ) { if ( ( string ) row [ `` Forename '' ] ! = record.Forename ) { // Do something } }
Is there a neat way to compare nullable and dbnullable objects ?
C#
I was just experimenting and ended up with the following snippet : I did n't realize that a method name alone was the same as an Action.What is making this so ?
public static class Flow { public static void Sequence ( params Action [ ] steps ) { foreach ( var step in steps ) step ( ) ; } } void Main ( ) { Flow.Sequence ( ( ) = > F1 ( ) , ( ) = > F2 ( ) ) ; Flow.Sequence ( F1 , F2 ) ; // < -- what makes this equiv to the line above ? } void F1 ( ) { } void F2 ( ) { }
What makes a name of a method equivalent to an action delegate ?
C#
Some simple rows of code below : When Visual Studio throws the null exception it references the following row and not the row where the exception occurred : I know the line number is correct when you view details of the problem . However , I often spend more time than necessary searching the wrong variables because the...
string [ ] countries = new string [ 1 ] ; string [ ] cities = new string [ 1 ] ; countries [ 0 ] = `` USA '' ; countries [ 1 ] = `` England '' ; cities [ 0 ] = `` Chicago '' ;
Why is Visual studio referencing the wrong row during exceptions ?
C#
I have 3 different patterns of address : which means : [ address ] [ , ] [ number ] [ - ] [ county ] [ , ] [ state ] [ - ] [ country ] I 'm trying to use this regex but not working correctly : Regex testerany help please ? ty
Avenue T , 55 - Sumiton , AL - USAAvenue T - Sumiton , AL - USASumiton , AL - USA ( ? < street > .*\ , ) ( ? : \s* ( ? < number > [ 1-9 ] [ 0-9 ] * ) ) ? \s* ( ? < county > .*\ , ) ? \s* ( ? < State > .*\- ) ? \s* ( ? < Country > . * )
Regex for 3 types of address
C#
Consider the following example : Despite the fact that both lines have SolidColorBrush and both have opacity=1 , a color blending still occurs : The pixel at the point of intersection is of darker red color.Why does it happen and how can I prevent it ? Thanks ! P.S Here is another example of the same code with the brus...
< Grid HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' > < Line Stroke= '' Red '' X1= '' 0 '' X2= '' 100 '' Y1= '' 50 '' Y2= '' 50 '' / > < Line Stroke= '' Red '' X1= '' 50 '' X2= '' 50 '' Y1= '' 0 '' Y2= '' 100 '' / > < /Grid > < Grid HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' > < ...
How to prevent colors from blending ?
C#
Here is my generic method code : I 'd want to set that generic IT must be only an interface . Is this possible ?
public static IT Activate < IT > ( string path ) { //some code here ... . }
Is possible to point that the type used for a generic method , should be an interface ?