lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have this code : I would like to not do the adding of a SeparatorTemplate BUT I would like to do the other tasks on the first run of the foreach . Does anyone have a suggestion on how I can do this ? I want to execute the rest of the code in the foreach but not the line adding the template on the first time around .
foreach ( var row in App.cardSetWithWordCounts ) { details.Children.Add ( new SeparatorTemplate ( ) ) ; // do some tasks for every row // in this part of the loop ... }
Is there a way I can determine which row I am on in a foreach loop ?
C#
Suppose I have a table in my database likeand I want every registrant to automatically be deleted , say , 100 days after registering . What is a proper way to do this , and what is the best way ? The shoddy way I was planning on doing it was going to be to create a sproc and in my server-side code invoke that sproc eve...
Registrants======================================================================= id | name | email | registration_date======================================================================= 1 | `` Sam '' | `` sammypie49 @ gmail.com '' | `` 2016-03-26T14:25:10 '' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -...
Best way in ASP.NET of configuring rows in a database to delete after a certain time
C#
I am stumped by EF 6 ... . I have a web application which behaves very badly in terms of performance . While analysing , I found one of the culprits being a method of mine that checks whether a collection is empty ( or not ) on an EF6 entity.Basically , I have : In my app , I need to check whether or not a given instan...
public partial class BaseEntity { public int BaseEntityId { get ; set ; } public string Name { get ; set ; } // a few more properties , of no concern here ... . // a lazily loaded collection of subitems public virtual ICollection < Subitem > Subitems { get ; set ; } } public partial class Subitem { public int SubitemId...
EF6 - not doing what I expected for .Any ( )
C#
I currently know of two ways to make an instance immutable in C # : Method 1 - Compile Time ImmutabilityMethod 2 - Readonly FieldsIt would be nice to have a guarantee that , some instance , once instantiated , will not be changed . const and readonly do this to a small degree , but are limited in their scope . I can on...
void Foo ( ) { // Will be serialized as metadata and inserted // as a literal . Only valid for compile-time constants const int bar = 100 ; } class Baz { private readonly string frob ; public Baz ( ) { // Can be set once in the constructor // Only valid on members , not local variables frob = `` frob '' ; } } var xs = ...
Achieving Local Runtime Immutability in C #
C#
I have a 2d arrow rotating to always face the a target ( the target in this case is the cursor ) , the pivot is my player character . I need to restrict this arrow to only follow the target if it is inside an angle of the player , an example would be 90 degrees , so it would only follow if the cursor is in the top righ...
public float speed ; public Transform target ; void Update ( ) { Vector2 mousePosition = Camera.main.ScreenToWorldPoint ( Input.mousePosition ) ; Vector2 direction = target.position - transform.position ; target.position = mousePosition ; float angle = Mathf.Atan2 ( direction.y , direction.x ) * Mathf.Rad2Deg ; Quatern...
Arrow rotating to face cursor needs to only do so while inside an angle made by two given directions
C#
I have something like this : As you can see this is done on Message.BodyI now what to do the same thing on other string properties on the Message class and I do n't want to duplicate all that code . Is there a way to do that by passing in the property somehow ?
public Expression < Func < Message , bool > > FilterData ( ) { switch ( this.operatorEnum ) { case FilterParameterOperatorEnum.EqualTo : return message = > ! string.IsNullOrEmpty ( message.Body ) & & message.Body .Equals ( this.value , StringComparison.InvariantCultureIgnoreCase ) ; case FilterParameterOperatorEnum.Not...
Returning Expression < > using various class properties
C#
I have a method that can be called from many threads , but I just want the 1st thread to do some logic inside the method . So , I 'm planning to use a boolean variable . The first thread that comes in , will set the boolean variable to false ( to prevent further threads to come inside ) , and execute the method logic.S...
private void myMethod ( ) { if ( firsTime ) //set to true in the constructor { firstTime = false ; //To prevent other thread to come inside here . //method logic } }
how to lock on a method content
C#
Simple code that I expect List < int > 's GenericTypeDefinition to contain a generic interface of ICollection < > . Yet I ca n't derive an acceptable type from List < int > which allows me to compare them properly.OutputI would have expected that r1 contained a type that was equal to b.EDITFixed , Jon Skeet gave me the...
using System ; using System.Collections.Generic ; using System.Linq ; public class Test { public static void Main ( ) { var a = typeof ( List < int > ) ; var b = typeof ( ICollection < > ) ; var r1 = a.GetGenericTypeDefinition ( ) .GetInterfaces ( ) ; foreach ( var x in r1 ) { Console.WriteLine ( x ) ; } Console.WriteL...
Comparing GenericTypeDefinition of interfaces
C#
I have two classes , A and B . B knows about A , and A does n't know about B . B has properties that can be nicely set from A , although there is no inheritance shared between A and B . There will be many times when I need to assign a B 's properties from an A , but I 'm looking for pointers on where I should put that ...
public class A { } public class B { //constructor ? public B ( A a ) { //set b 's properties from a } //factory method ? public static B FromA ( A a ) { B b = new B ( ) ; //set b 's properties from a return b ; } //setter method ? public static void SetBFromA ( B b , A a ) { //set b 's properties from a } //assignment ...
Conventions in assignment code ?
C#
Example 1 : vsExample 2 : Is there any benefit to using the first method over the second , or vice versa ?
SomeObject someObject = new SomeObject ( ) ; if ( someObject.Method ( ) ) { //do stuff } //someObject is never used again if ( new SomeObject ( ) .Method ( ) ) { //do stuff }
Is there a benefit to storing an object in a variable before calling a method on it ?
C#
I am using below method to convert byte [ ] to Bitmap : Just wondering if I need to free up any resources here ? Tried calling Marshal.FreeHGlobal ( ptr ) , but I am getting this error : Invalid access to memory location.Can anyone please guide ? Also , FYI , I could use MemoryStream to get Bitmap out of byte [ ] , but...
public static Bitmap ByteArrayToBitmap ( byte [ ] byteArray ) { int width = 2144 ; int height = 3 ; Bitmap bitmapImage = new Bitmap ( width , height , PixelFormat.Format32bppPArgb ) ; BitmapData bmpData = bitmapImage.LockBits ( new Rectangle ( 0 , 0 , width , height ) , ImageLockMode.ReadWrite , PixelFormat.Format32bpp...
Marshal - Do I need to free any resources ?
C#
I have two classes ( or models rather ) having some common properties . For instance : I need to write a method that can accept a member selector expression where the member to select can come from either of the two models . This is what I mean : Please note that the selector passed selects both from Model1 and also fr...
public class Model1 { public int Common1 { get ; set ; } public int Common2 { get ; set ; } public int Prop11 { get ; set ; } public int Prop12 { get ; set ; } } public class Model2 { public int Common1 { get ; set ; } public int Common2 { get ; set ; } public int Prop21 { get ; set ; } public int Prop22 { get ; set ; ...
Member selector expression combining two classes
C#
I 'm trying to create a wpf project without using auto generate files in VS2010 , I thought it would help me to get a better understanding so I hope this wo n't sound super primitive question . Anyway , after making the xaml file and its code behind e.g . myWindow.xaml and myWindow.xaml.cs I also created App.xaml and i...
< Application x : Class= '' test1.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' StartupUri= '' myWindow.xaml '' > < Application.Resources > < /Application.Resources > < /Application > namespace test1 { /// < summary > /// ...
Making a WPF project manually
C#
After a build environment update , one of our Smoke Tests broke in TeamCity . Investigation turned out that from the same source code , C : \Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe produces correct binaryC : \Program Files ( x86 ) \MSBuild\14.0\bin\MSBuild.exe produces incorrect binaryWhen does this occu...
static void Main ( string [ ] args ) { var customerId = Guid.NewGuid ( ) ; // Produces buggy code when compiled with MSBuild v14 TestMethodWithParams ( args : customerId , whatever : `` foo '' ) ; //All the calls below result correct behavior , regardless of the version of MSBuild , order and naming of parameters TestM...
MSBuild v14 compiles a semantically incorrect assembly under some rare circumstances
C#
i do n't want to say : i want something like : Is this possible or is there also something else besides ! = .
( trsaz ! = v1 ) & & ( trsaz ! = v2 ) & & ... trsaz ! = ( v1 , v4 , v7 , v11 )
How do i say is not , is not
C#
This question occurred to me when an answer was proposed to another question I asked . Suppose I have a base classwith some decent number of derived classes- let 's say more than half a dozen . Most of those derived classes share no similarity beyond what they inherit from the base class , but two of them have a simila...
public abstract class BaseClass { } public class OneOfMyDerivedClasses : BaseClass { public string SimilarProperty { get ; set ; } //Other implementation details } public class AnotherOneOfMyDerivedClasses : BaseClass { public string SimilarProperty { get ; set ; } //Other implementation details , dissimilar to those i...
How aggressively should I subclass to keep DRY ?
C#
I would like to check in runtime that a variable of type Func < ... > is a specific class method.E.g .
class Foo { public static int MyMethod ( int a , int b ) { // ... } } Func < int , int , int > myFunc ; myFunc = Foo.MyMethod ; if ( myFunc is Foo.MyMethod ) { //do something }
How to check if a variable of type Func < ... > is a specific class method
C#
How can I call this constructor ? I thought of but I want to avoid object creation.So is this one ok ?
public class DataField { public String Name ; public Type TheType ; public DataField ( string name , Type T ) { Name = name ; TheType = T ; } } f = new DataField ( `` Name '' , typeof ( new String ( ) ) ) ; f = new DataField ( `` Name '' , String ) ;
How to pass a type to a method ?
C#
I am learning OOP and have a question about what is exactly happening with the code below.I have the classic Dog Animal example going . Dog inherits Animal.Both questions are based on this assignment : Animal a = new Dog ( ) ; What is actually happening when I declare an Animal and set it to a Dog reference . Is there ...
public class Animal { public string Name { get ; set ; } public virtual string Speak ( ) { return `` Animal Speak '' ; } public string Hungry ( ) { return this.Speak ( ) ; } } public class Dog : Animal { public override string Speak ( ) { return `` Dog Speak '' ; } public string Fetch ( ) { return `` Fetch '' ; } }
What is happening with inheritance in my example ? And , what is the proper terminology in c # ?
C#
I have a XAML UserControl embedded in a WinForms/WPF Interop ElementHost control . The control is pretty simple - it 's just a dropdown with a button - here 's the entire markup : The problem is that it does n't work reliably , and far from instinctively.If I type something in the box that actually matches an item , no...
< UserControl x : Class= '' Rubberduck.UI.FindSymbol.FindSymbolControl '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schema...
Why does my dropdown feel so clunky ?
C#
I am writing a function for an item service where if the user requests for all items under a certain name it will return them all . Such as all the phones that are iPhone X 's etc.I got help to make one of the functions work where if there are more than 1 items it will return them all ( this is the third case ) : What ...
var itemsList = items.ToList ( ) ; switch ( itemsList.Count ( ) ) { case 0 : throw new Exception ( `` No items with that model '' ) ; case 1 : return itemsList ; case { } n when n > 1 : return itemsList ; } return null ;
What is the purpose of the parenthesis in this switch and case label ?
C#
I 'm constructing arbitrary objects from DataRows using Reflection , and when the rubber finally meets the road , I need to take a value from the DataRow and assign it to the property on the object.Because DataRows can be full of types that do n't support conversion , many of these result in exceptions that have to be ...
public void Merge ( DataRow data ) { PropertyInfo [ ] props = this.GetType ( ) .GetProperties ( BindingFlags ... ) ; foreach ( PropertyInfo pi in props.Where ( p = > T_IsPrimitive ( p.PropertyType ) ) ) { object src = null ; if ( dataAsDataRow.Table.Columns.Contains ( pi.Name ) ) src = ( ( DataRow ) data ) [ pi.Name ] ...
Is there any way to test my conversions to avoid using exceptions ?
C#
The Microsoft.Office.Interop.Word._Document interface has a method with the following signature : A few points I am having trouble understanding : A ref parameter can not have a default value.A default value has to be a constant , and Type.Missing is not.When calling this method , I can use Close ( false ) - normally a...
void Close ( ref object SaveChanges = Type.Missing , ref object OriginalFormat = Type.Missing , ref object RouteDocument = Type.Missing ) ;
Understand COM c # interfaces
C#
I have the following snippet : It treats x @ product.Count as a literal . How can I have a character placed right before the @ symbol ?
< ul > @ foreach ( var product in Model.Products ) { < li > @ product.Name x @ product.Count < /li > } < /ul >
Why does n't razor detect this as a code block in ASP.NET MVC ?
C#
I do n't understand the order of execution in the following code . Here the numbers that satisfied the first Where clause are ( 4 , 10 , 3 , 7 ) , and the numbers that satisfied the second Where clause are 2 and 1 , after that we have function Aggregate that subtract them and make one element from both . My question is...
var ints = new int [ ] { 2 , 4 , 1 , 10 , 3 , 7 } ; var x = ints .Where ( c = > c / 3 > 0 ) < -- ( 1 ) .Select ( s2 = > s2 + ints .Where ( c = > c / 3 == 0 ) < -- ( 2 ) .Aggregate ( ( f , s ) = > f - s ) ) .Sum ( ) ;
LINQ execution flow ( homework )
C#
I have encountered a performance issue in .NET Core 2.1 that I am trying to understand . The code for this can be found here : https : //github.com/mike-eee/StructureActivationHere is the relavant benchmark code via BenchmarkDotNet : From the outset , I would expect Activated to be faster as it does not store a local v...
public class Program { static void Main ( ) { BenchmarkRunner.Run < Program > ( ) ; } [ Benchmark ( Baseline = true ) ] public uint ? Activated ( ) = > new Structure ( 100 ) .SomeValue ; [ Benchmark ] public uint ? ActivatedAssignment ( ) { var selection = new Structure ( 100 ) ; return selection.SomeValue ; } } public...
Is Activating a Struct Without Storing It as a Local Variable Expected to Be Slower than Not Storing It as a Local Variable ?
C#
We are indexing documents into Solr using Solrnet in asp.net c # project . We are having requirement where Solr DIH can not be used , so we are indexing products in certain batches to Solr using following code : With huge document size , it takes lot of time ( most of times it takes few hours ) to complete whole proces...
decimal cycleCount = ProductCount / batchSize ; for ( int i = 0 ; i < = Math.Round ( cycleCount ) ; i++ ) { var Products = Products ( batchSize , languageId , storeId ) .ToList ( ) ; solrCustomWorker.Add ( solrProducts ) ; solrCustomWorker.Commit ( ) ; }
Stop the for-loop in-between before it completes
C#
I am working on a small project using C # and EF5.0 and I need to group some data . Let say I have table of columns in a building like shown below.I need a C # code to see the above data groupped like this : I prefer clues than the exact solution.EDIT : Below code shows my current state . I think I can find the columns...
+ -- -- -- -- -- + -- -- -- -- Columns Table -- + -- -- -- + -- -- -- +| ColumnID |ColumnName|Width|Length|Height|number| + -- -- -- -- -- + -- -- -- -- -- + -- -- -+ -- -- -- + -- -- -- + -- -- -- +| 1 | C101 | 50 | 70 | 250 | 1 | | 2 | C102 | 70 | 70 | 250 | 1 | | 3 | C103 | 70 | 60 | 250 | 1 | | 4 | C104 | 90 | 70 |...
Data grouping in SQL
C#
While refactoring some code written by someone else , I 've come across some weirdness that I do n't understand , and I 'm hoping someone can explain why it happens.What I thought would happen here would be that as brackets have the highest precedence , the assignment inside the brackets would happen first and none of ...
if ( mystring.Length ! = ( mystring = mystring.Replace ( `` ! # '' , replacement ) ) .Length ) { i = 1 ; } else if ( mystring.Length ! = ( mystring = mystring.Replace ( `` # '' , replacement ) ) .Length ) { i = -1 ; } mystring = mystring.Replace ( `` ! # '' , replacement ) ; if ( mystring.Length ! = mystring.Length ) {...
Evaluation of expressions within an if statement
C#
A piece of C # code I got result false in code execution , but when I copy that code into WATCH window , the result is true .
var isTrue = ( new List < int > { 1,2,3 } is IEnumerable < object > ) ;
VS debug issue , who can help me to explain this below ?
C#
Ive got what I think may be an unusual problem ( Ive searched around a lot for an answer , but I dont think Ive found one ) .I have messages that are read from a queue and depending on the message type contains a payload that needs to be deserialized into a concrete c # class . This needs to eventually be concrete ( I ...
public abstract class BaseRuleMessage < T > { public abstract Func < T , bool > CompileRule ( Rule r , T msg ) ; public T Deserialize ( ClientEventQueueMessage message ) { return JsonConvert.DeserializeObject < T > ( message.Payload ) ; } public BaseRuleMessage ( ) { RulesCompleted = new List < int > ( ) ; } public IEn...
Factory class using generics but without base class
C#
I have textbox that I use for diagnostic purposes . The code behind is really simple : XAML : C # : How can I define that each new input is on a different line ? Because right now all errors are in just 1 long line . 14:15:00 Error 1 14:16:00 Error 2 14:17:00 Error 3Instead of readable with line breaks between each err...
< TextBox HorizontalAlignment= '' Left '' Margin= '' 640,20,0,0 '' TextWrapping= '' Wrap '' Height= '' 280 '' Width= '' 840 '' Name= '' txtDiagnostic '' IsHitTestVisible= '' True '' / > private void AddMessage ( string message ) { txtDiagnostic.Text += ( DateTime.Now.ToString ( `` hh : mm : ss : fff '' ) + `` `` + mess...
Next text input on different line
C#
I have a class that looks like this : For the moment , I have each of the first 3 methods call SomeSpecialMethod ( ) just before these method return . I 'm going to add about 15 more methods that in the end all need to execute SomeSpecialMethod ( ) and I 'm wondering if there 's a way to say `` when any of the methods ...
public class SomeClass { public void SomeMethod1 ( ) { ... } public void SomeMethod2 ( ) { ... } public void SomeMethod3 ( ) { ... } private void SomeSpecialMethod ( SomeParameter ) { ... } }
executing a method after several methods run
C#
Basically I have an object rotating . It is a click and drag type of rotation , but when the object is facing the -z -x corner , or bottom left corner , it has a chance of completely flipping 180 degrees the opposite way when clicked again . This is very troublesome and I even know what line this takes place in . Here ...
void OnMouseDown ( ) { Vector3 pos = Camera.main.WorldToScreenPoint ( transform.position ) ; pos = Input.mousePosition - pos ; baseAngle = Mathf.Atan2 ( pos.y , pos.x ) * Mathf.Rad2Deg ; baseAngle -= Mathf.Atan2 ( transform.right.y , transform.up.x ) * Mathf.Rad2Deg ; startRotation = transform.rotation ; }
Object flips 180 degrees on z-axis in -z and -x corner
C#
I 've a ListView whose data I select and send to a DataGrid . I am having trouble with the quantity column of the DataGrid which I would want to calculate how many times a ListView item has been added to the said DataGrid ( I 'm currently displaying a success message when the same item is selected ) . I would also want...
< ListView x : Name= '' ItemGridView '' ItemsSource= '' { Binding Items } '' SelectedItem= '' { Binding SelectedItem } '' PreviewMouseDoubleClick= '' ItemGridView_PreviewMouseDoubleClick '' > < ListView.View > < GridView AllowsColumnReorder= '' False '' > < GridViewColumn > < GridViewColumn.CellTemplate > < DataTemplat...
How to Add a Quantity Column on a DataGrid from ListView selection in WPF
C#
At first , I do not use dynamic , I just use the code like this , and it works well.But when I change it to dynamic,it is wrong.and I add a method like this , I build the project it show that List do not have the AsQueryable method.How to change it ?
List < Student > result2 = StudentRepository.GetStudent ( sex , age ) .ToList ( ) ; IQueryable rows2 = result2.AsQueryable ( ) ; dynamic result = GetPeopleData ( sex , age ) ; IQueryable rows = result.AsQueryable ( ) ; private dynamic GetPeopleData ( int sex , int age ) { if ( sex > 30 ) return StudentRepository.GetStu...
What is the difference between my codes when I use 'dynamic ' to use AsQueryable method ?
C#
I am trying to post a file to an iManage server REST interface ( Apache server , java backend ? ? not sure ) . Postman works fine , but when I try it from C # .NET CORE 3.1 I get a response like so : { `` error '' : { `` code '' : `` FileUploadFailure '' , '' message '' : `` File upload failure '' } } Anyone have any i...
< PackageReference Include= '' Newtonsoft.Json '' Version= '' 12.0.3 '' / > using Newtonsoft.Json ; using System ; using System.Net.Http ; using System.IO ; using System.Text ; using System.Net.Http.Headers ; using System.Threading.Tasks ; namespace ConsoleApp1 { class Program { static async Task Main ( string [ ] args...
Can not Upload File using C # HttpClient , Postman works OK
C#
I 'm attempting to create a JSON request to send to email service GetResponse to add a contact to a mail campaign.The format I 'm trying to achieve is for add_contactFollowing How to create JSON string in C # I contructed this setupAnd filled this like soHere json is as expectedWhat I do n't know is how to properly add...
[ `` API_KEY '' , { `` campaign '' : `` CAMPAIGN_ID '' , `` action '' : `` action_value '' , `` name '' : `` name_value '' , `` email '' : `` email_value '' , `` cycle_day '' : cycle_day_value , `` ip '' : `` ip_value '' , `` customs '' : [ { `` name '' : `` name_1_value '' , `` content '' : `` content_1_value '' } , {...
Creating a specific JSON format
C#
I was trying to better understand string 's interning in c # and got into the following situation : I 'm getting the following result in console : True True True False The mistake for me is that why is the 4th false ?
string a = '' Hello '' ; string b = '' Hello '' ; string c = new string ( new char [ ] { ' H ' , ' e ' , ' l ' , ' l ' , ' o ' } ) ; string d = String.Intern ( c ) ; Console.WriteLine ( a==b ) ; Console.WriteLine ( c==d ) ; Console.WriteLine ( ( object ) a== ( object ) b ) ; Console.WriteLine ( ( object ) c== ( object ...
False after casting interned strings to objects
C#
Possible Duplicate : When do you use code blocks ? Ok , this might be a stupid question and I might be missing something obvious but as I slowly learn C # this has kept nagging me for a while now.The following code obviously compiles just fine : I understand that { } blocks can be used for scoping . The question is why...
public void Foo ( ) { { int i = 1 ; i++ ; } { int i = 1 ; i -- ; } }
Benefits of scoping blocks ?
C#
I have one array : I m looking for the index of BMW , and I using below code to get : Unfortunately it return the result for the first BMW index only . Current output : My expected output will be
string [ ] cars = { `` Volvo '' , `` BMW '' , `` Volvo '' , `` Mazda '' , '' BMW '' , '' BMW '' } ; Label1.Text = Array.FindIndex ( filterlistinput , x = > x.Contains ( `` BMW '' ) ) .ToString ( ) ; 1 { 1,4,5 }
Get the list of index for a string in an array ?
C#
I wanted to do trim by default white-space characters and by my additional characters . And I did this by following way : As for me it is looks like stupid , because it has more iterations than it needs . Is it possible to add characters ( instead replace defaults ) for string.Trim ( ) ? Or where can I found array of '...
string MyTrim ( string source ) { char [ ] badChars = { ' ! ' , ' ? ' , ' # ' } ; var result = source.Trim ( ) .Trim ( badChars ) ; return result == source ? result : MyTrim ( result ) ; }
Is it possible to add characters ( instead replace defaults ) for string.Trim ( ) ?
C#
Here is a seemingly simple class to sum all elements in an array : Of course this is not an efficient way to perform this task . And this is also very inefficient usage of threads . This class is written to illustrate a basic divide and conquer solution concept , and it hopefully does so.Here is also a simple unit test...
class ArraySum { class SumRange { int left ; int right ; int [ ] arr ; public int Answer { get ; private set ; } public SumRange ( int [ ] a , int l , int r ) { left = l ; right = r ; arr = a ; Answer = 0 ; } public void Run ( ) { if ( right - left == 1 ) { Answer = arr [ left ] ; } else { SumRange leftRange = new SumR...
Incorrect result with too many threads
C#
I read a lot of articles about number format string , ex : http : //msdn.microsoft.com/en-us/library/0c899ak8.aspxI really not understand how to write the best format string . To get a excepted result , I can write some ways . Example : print number 1234567890 as a text `` 1,234,567,890 '' . These ways give the same re...
1234567890.ToString ( `` # , # '' ) 1234567890.ToString ( `` # , # # '' )
How to get the best number format string ?
C#
I have these two functions which read a stream into a buffer and loads it into the given struct.I 'd like to combine these into a generic function to take either of the structs , I 'm just unsure what the proper way to do this is.Is this the correct way ?
TestStruct1 ReadRecFromStream2 ( Stream stream ) { byte [ ] buffer = new byte [ Marshal.SizeOf ( typeof ( TestStruct1 ) ) ] ; stream.Read ( buffer , 0 , 128 ) ; GCHandle handle = GCHandle.Alloc ( buffer , GCHandleType.Pinned ) ; try { return ( TestStruct1 ) Marshal.PtrToStructure ( handle.AddrOfPinnedObject ( ) , typeo...
How to make these struct functions generic ?
C#
I recently stumbled upon an odd issue which I could not explain and I would be glad if someone could clarify why it happens.The issue I 've encountered is as follows : I have an interface which is implemented , like so : And another interface which is implemented in a different project , like so : I have an object whic...
namespace InterfaceTwo { public interface IA { } } namespace InterfaceTwo { public class A : IA { } } namespace InterfaceOne { public interface IB { } } namespace InterfaceOne { public class B : IB { } } using InterfaceOne ; using InterfaceTwo ; namespace MainObject { public class TheMainObject { public TheMainObject (...
Object instantiation fails when using overloaded constructor
C#
So I took a look at ILDASM , inspecting a .exe which looks like this : Now , the CIL code looks like that : I understand that first b is loaded ( which is stored at [ 1 ] ) , then a constant with the value of 1 and then they are compared . What I do not understand is why another constant with the value 0 is loaded and ...
int a = 2 ; Int32 b = 1 ; if ( b == 1 ) { } IL_0005 : ldloc.1IL_0006 : ldc.i4.1IL_0007 : ceqIL_0009 : ldc.i4.0IL_000a : ceqIL_000c : stloc.2 .method private hidebysig instance void Form1_Load ( object sender , class [ mscorlib ] System.EventArgs e ) cil managed { // Code size 19 ( 0x13 ) .maxstack 2.locals init ( [ 0 ]...
What exactly does the == operator do ?
C#
Using TPL with .NET 4 , I 'm trying to decide how to design APIs that deal with futures . One possibility that occurred to me was to mimic the async pattern but without an End ( IAsyncResult ) method : As such , callers can decide whether to call the blocking or non-blocking version of GetAge ( ) . Moreover , they have...
public Task < int > BeginGetAge ( ) { // create and return task } public int GetAge ( ) { return this.BeginGetAge ( ) .Result ; }
Does this TPL idiom exist ?
C#
Here is some example code : Since DateTime can not be null , why does this code compile ? Edit : The issue is not just that this code will always return false , but why something like DateTime which is never null is allowed in such a comparison .
static DateTime time ; if ( time == null ) { /* do something */ }
Why is this a valid comparison
C#
I have 2 linq statements - currently in the middle of a switch block . The statements are below.As you can see the only difference is that they refer to two different properties of `` lender '' , however , all the elements used in the linq query are identical in `` ApplicationWindows '' and `` TransferWindows '' , alth...
pwStartTime = lender.ApplicationWindows.Where ( w = > w.Name == pwPeriod & & w.EndTime.TimeOfDay > dateToCheck.TimeOfDay ) .Select ( w = > w.StartTime ) .FirstOrDefault ( ) ; pwStartTime = lender.TransferWindows.Where ( w = > w.Name == pwPeriod & & w.EndTime.TimeOfDay > dateToCheck.TimeOfDay ) .Select ( w = > w.StartTi...
Is it possible to make 1 generic method out of these 2 linq statements ?
C#
In the following example , I have two constraints , Foobar and IFoobar < T > , on type T in generic class FoobarList < T > . But the compiler gives an error : Can not implicitly convert type 'Foobar ' to 'T ' . An explicit conversion exists ( are you missing a cast ? ) It seems the compiler considers CreateFoobar as a ...
interface IFoobar < T > { T CreateFoobar ( ) ; } class Foobar : IFoobar < Foobar > { //some foobar stuffs public Foobar CreateFoobar ( ) { return new Foobar ( ) ; } } class FoobarList < T > where T : Foobar , IFoobar < T > { void Test ( T rFoobar ) { T foobar = rFoobar.CreateFoobar ( ) ; //error : can not convert Fooba...
Priorities of multiple constraints on a generic type parameter
C#
I wonder what is the reason for the invocation of the method that prints `` double in derived '' . I did n't find any clue for it in the C # specification .
public class A { public virtual void Print ( int x ) { Console.WriteLine ( `` int in base '' ) ; } } public class B : A { public override void Print ( int x ) { Console.WriteLine ( `` int in derived '' ) ; } public void Print ( double x ) { Console.WriteLine ( `` double in derived '' ) ; } } B bb = new B ( ) ; bb.Print...
C # Overloaded method invocation with Inheritance
C#
In the given class I 've specified a generic as the type to extend via the this keyword . Being that I 've delayed the definition of the type until compile time , how does intellisense ( and anything else involved ) know what type I am extending ? Does C # simply default to the top level System.Object ?
public static class MyClass { public static void Print < T > ( this T theObject ) { Console.WriteLine ( `` The print output is `` + theObject.ToString ( ) ) ; } }
What are we extending when creating a generic extension method ?
C#
I have two datatables , I am trying to copy row from one table to another , I have tried this . the thing is that my tables are not exactly the same , both tables have common headers , but to the second table have more columns , therefore I need `` smart '' copy , i.e to copy the row according to the column header name...
+ -- -- -- -- + -- -- -- -- + -- -- -- -- +| ID | aaa | bbb |+ -- -- -- -- + -- -- -- -- + -- -- -- -- +| 23 | value1 | value2 | < -- -- copy this row + -- -- -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- +| ID | ccc | bbb | aaa |+ -- -- -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- +| 23 | | value2 | value1 | < --...
Copy row from datatable to another where there are common column headers
C#
In my page load , am I calling ReturnStuff ( ) once or three times ? If I am calling it three times , is there a more efficient way to do this ?
protected void Page_Load ( object sender , EventArgs e ) { string thing1 = ReturnStuff ( username , password ) [ 0 ] ; string thing2 = ReturnStuff ( username , password ) [ 1 ] ; string thing3 = ReturnStuff ( username , password ) [ 2 ] ; } public static List < string > ReturnStuff ( string foo , string bar ) { // Crea...
Am I using Lists correctly ?
C#
Is there a way to shrink these into just one group result ? I have a set of pages like these which simply return static content and thought there must be a more efficient way to do it . EDIT : Thanks for all the replies : )
public ActionResult Research ( ) { return View ( ) ; } public ActionResult Facility ( ) { return View ( ) ; } public ActionResult Contact ( ) { return View ( ) ; }
Can I simplify this code for return views ? It seems very redundant
C#
I was hoping someone might help me understand why Convert.ToDecimal when used within linq is rounding a decimal and when used outside , it does notGiven the following DB : CODE : Output
CREATE TABLE [ dbo ] . [ Widgets ] ( [ ID ] [ int ] NOT NULL , [ WidgetName ] [ varchar ] ( 50 ) NOT NULL , [ UnitsAvailable ] [ int ] NOT NULL , [ WeightInGrams ] [ decimal ] ( 10 , 6 ) NULL ) ON [ PRIMARY ] GOINSERT [ dbo ] . [ Widgets ] VALUES ( 1 , N'Best thing ever ' , 100 , CAST ( 10.000210 AS Decimal ( 10 , 6 ) ...
Why is Convert.ToDecimal returning different values
C#
Though I can successfully do this at the top of a page : and then use a class like this later : I really would like to do this : so that I can use it like this later : but that gives me the error : The 'tagprefix ' attribute can not be an empty string.Is n't there a way to register an empty TagPrefix so it can be used ...
< % @ Register TagPrefix= '' me '' Namespace= '' MyNamespace '' % > < Usercontrol : DataRowTextBox ... > < Regexes > < me : RegularExpressionValidatorItem Type= '' USPhoneNumber '' / > < me : RegularExpressionValidatorItem Type= '' InternationalPhoneNumber '' / > < /Regexes > < /Usercontrol : DataRowTextBox > < % @ Reg...
Use an empty TagPrefix with a < % @ Register % >
C#
I have a list of objects of the same type that each has a property that is an array of floats . Taking this list as input , what is the easiest way to return a new array that is the average of the arrays in the list ? The input objects look like this : The DataValues arrays will be guaranteed to have the same length . ...
Class MyDatas { float [ ] DataValues ; } ... List < MyDatas > InputList ; float [ ] result ;
Elegant averaging of arrays from different instances of an object in C #
C#
After reading Stephen Cleary blog post about eliding async and await I 've decided to go and play around with it . I wrote very simple console app with HttpClient using Visual Studio For Mac.According to blog post it should throw an exception but it did n't . If I switch to Windows and try to run this app , I will get ...
public static async Task Main ( string [ ] args ) { Console.WriteLine ( await Get ( ) ) ; Console.WriteLine ( `` Hello World ! `` ) ; } public static Task < string > Get ( ) { using ( var http = new HttpClient ( ) ) return http.GetStringAsync ( `` http : //google.com '' ) ; }
Eliding async and await on HttpClient is not throwing exception on OSX
C#
I am using Entity Framework 4.3.1 using the DbContext POCO approach against a SQL Server 2012 database . I have just two tables in the database and they look like this : NOTE : There are no foreign keys specified in the database at all - I am only enforcing the relationship in the model ( I can not change the database ...
public class Two { public long TwoId { get ; set ; } public string OneId { get ; set ; } public virtual One One { get ; set ; } } public class One { public string OneId { get ; set ; } public DateTime DeliveryDate { get ; set ; } public virtual ICollection < Two > Twos { get ; private set ; } public void AddTwo ( Two t...
Why would a datetime prevent a navigation property from getting loaded ?
C#
I am working on some class room examples . This code works but I do not see why it works . I know that there is a generic type and that class implements Item but Item is just another class . Why would this code allow a int and double into the same list.I am sure that it has to do with the Generic but why I am not reall...
public class Item < T > : Item { } public class Item { } static void Main ( string [ ] args ) { var list = new List < Item > ( ) ; list.Add ( new Item < int > ( ) ) ; list.Add ( new Item < double > ( ) ) ; }
Why does this code work for different types ?
C#
I am new to CSharp.I have seen `` this ( ) '' in some code.My question is Suppose if i callParemeterized constructor , am i invoking the paremeterless constructor forcefully ? .But According to constructor construction , i believe parameterless constructor will be executed first.Can you please explain this with simple ...
public OrderHeader ( ) { } public OrderHeader ( string Number , DateTime OrderDate , int ItemQty ) : this ( ) { // Initialization goes here ... . }
Using this ( ) in code
C#
For example , if I have a class : and later create two instances of it : and call r sequentially , the r for both will give the same values . I 've read that this is because the default constructor for Random uses the time to provide `` randomness , '' so I was wondering how I could prevent this . Thanks in advance !
public class Class { public Random r ; public Class ( ) { r= new Random ( ) } } Class a = new Class ( ) ; Class b = new Class ( ) ;
How do I have two randoms in a row give different values ?
C#
I know other people wrote similar questions , but I think mine is a different case , since I could n't find any solution.I have an object assignment , something very simple like this : the assembly code generated is the followingnow , just for to understand what 's going on , I wanted to step inside the call ( why a ca...
_buffer3 = buffer ; //they are just simple reference types mov edx , dword ptr [ ebp-3Ch ] mov eax , dword ptr [ ebp-40h ] lea edx , [ edx+4 ] call 69C322F0 69C322F0 ? ? ? private class Test { int _X ; int _Y ; Test _t ; public void SetValues ( int x , int y , Test t ) { _X = x ; _Y = y ; } } _X = x ; 00000028 mov eax ...
Mysterious call is added when reference is assigned in c #
C#
I have a view that displays a boolean ( currently defaulted to 0 ) in a box format in the view that I can not check to activate as true and also want to enter text in the result field to pass back to the controller and save both changes to a table . Can someone please explain what I have to do to allow this functionali...
public ActionResult P1A1Mark ( ) { List < MarkModel > query = ( from row in db.submits where row.assignment_no.Equals ( `` 1 '' ) & & row.group_no == 1 group row by new { row.assignment_no , row.student_no , row.student.firstname , row.student.surname } into g select new MarkModel { student_no = g.Key.student_no , stud...
Enable boolean and enter text in view then pass back to controller - MVC
C#
I 've seen most people use member variables in a class like : But what 's the difference of that to this ?
string _foo ; public string foo { get { return _foo ; } ; private set { _foo = value } ; } public string foo { get ; private set ; }
Why use member variables in a class
C#
Does anybody know how to write an extension function returning a ParallelQuery in PLINQ ? More specifically , I have the following problem : I want to perform a transformation within a PLINQ query that needs an engine , whose creation is costly and which can not be accessed concurrently.I could do the following : Here ...
var result = source.AsParallel ( ) .Select ( ( i ) = > { var e = new Engine ( ) ; return e.Process ( i ) ; } ) // helper class : engine to use plus list of results obtained in thread so farclass EngineAndResults { public Engine engine = null ; public IEnumerable < ResultType > results ; } var result = source.AsParallel...
How do I write a thread-aware extension function for PLINQ ?
C#
In Haskell , the language I 'm most familiar with , there is a fairly precise way to determine the type of a variable . However , in the process of learning C # , I 've become somewhat confused in this regard . For example , the signature for the Array.Sort method is : Yet , this method will raise an exception if the a...
public static void Sort ( Array array )
How do I determine the appropriate type for method parameters in C # ?
C#
This is the xml stream : The corresponding classes look like this : the code to deserialise the xml ( the string replacement contains the xml code ) : The method stringToStreamThe result that i get is as following : The object XmlData is made and there is a list of taskEvents.The problem is in the list itself : it is e...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < historydetails > < taskEvent > < eventtype > Transitions < /eventtype > < historyevent > Task moved < /historyevent > < details > From 'Requested ' to 'In Validation ' < /details > < author > NAme < /author > < entrydate > 01 Jul 13 , 11:34 < /entrydate > < history...
deserialising does not work
C#
I have seen people define their events like this : Can somebody explain how this is different from defining it without it ? Is it to avoid checking for null when raising the event ?
public event EventHandler < EventArgs > MyEvent = delegate { } ;
Why is this event declared with an anonymous delegate ?
C#
This is probably a very beginner question but I have searched a lot of topics and could n't really find the same situation , although I 'm sure this kind of situation happens all the time.My project/program is going to track changes to drawings on construction projects and send notifications to people when drawings are...
public class Project { private readonly List < Drawing > _drawings = new List < Drawing > ( 30 ) ; private readonly List < Person > _autoRecepients = new List < Person > ( 30 ) ; public int ID { get ; private set ; } public string ProjectNumber { get ; private set ; } public string Name { get ; private set ; } public b...
Circular reference — architecture question
C#
Given the code block above does not actually do anything but call the first DoSomethingElse method , what would be a clever approach to having the correct method call based on the real type of the parameters passed to the DoSomething method ? Is there a way I can get the method call resolved at runtime , or do I have t...
class Base { } class ClassA : Base { } class ClassB : Base { } public static class ExtensionFunctions { public static bool DoSomething ( this Base lhs , Base rhs ) { return lhs.DoSomethingElse ( rhs ) ; } public static bool DoSomethingElse ( this Base lhs , Base rhs ) { return true ; } public static bool DoSomethingEls...
C # enhanced Method overload resolution
C#
Calling _thread.Join ( ) causes the GetConsumingEnumerable loop to be stuck on the last element . Why does this behavior occur ? The context for this approach is that I need to make sure that all operations are executed on one OS thread , which would allow a part of the app to use different credentials than the main th...
public abstract class ActorBase : IDisposable { private readonly BlockingCollection < Task > _queue = new BlockingCollection < Task > ( new ConcurrentQueue < Task > ( ) ) ; private readonly Thread _thread ; private bool _isDisposed ; protected ActorBase ( ) { _thread = new Thread ( ProcessMessages ) ; _thread.Start ( )...
Thread Join ( ) causes Task.RunSynchronously not to finish
C#
In C # you are recommended to add the [ Flags ] attribute to bitmask enumerations , like so : I discovered I had code that erroneously performed bitwise operations on an enumeration without the [ Flags ] attribute that was not a bitmask at all ( First=1 , Second=2 , Third=3 , etc. ) . This was of course logically wrong...
[ Flags ] public enum Condiments { None = 0 , Ketchup = 1 , Mustard = 2 , Mayo = 4 , Pickle = 8 , AllTheWay = 15 }
Possible to prevent accidental bitwise operators on non-bitmask field ?
C#
I 'm trying to write an extension method that , given a value , will returnThe value itself if it 's different from DBNull.ValueThe default value for value 's typeYeah , that 's not the clearest explanation , maybe some code will make what I 'm trying to accomplish obvious.As long as value 's boxed type is the same as ...
public static T GetValueOrDefault < T > ( this object value ) { if ( value == DBNull.Value ) return default ( T ) ; else return ( T ) value ; }
Casting boxed byte
C#
I have an Item class that has a publicly accessible member NoSetter that does not contain a setter . The object does explicitly state a get , which retrieves a private readonly List object.When you create this object , you ca n't set NoSetter to a list , the compiler fails whenever you try . However if you create the l...
class Item { private readonly List < string > emptyString ; public Item ( ) { this.emptyString = new List < string > ( ) ; } public List < string > NoSetter { get { return this.emptyString ; } } } List < string > goldenString = new List < string > ( ) ; goldenString.Add ( `` Nope '' ) ; Item item = new Item ( ) { NoSet...
How does an inline list override a property with no setter ?
C#
i have code . the constructor should enter the GetItems function but when i place breakpoint , it simply do not stop.what is the problem ?
namespace Storehouse { public partial class MainForm : Form { public MainForm ( ) { InitializeComponent ( ) ; var a = GetItems ( fILEToolStripMenuItem ) ; } public IEnumerable < ToolStripMenuItem > GetItems ( ToolStripMenuItem item ) { foreach ( ToolStripMenuItem dropDownItem in item.DropDownItems ) { if ( dropDownItem...
constructor do not enter a function C #
C#
I ran into an issue the other day that I first believed to be an issue with Entity Framework . I posted a question about it the other day here . Since then , I have determined that this issue is not related to Entity Framework.Consider the following classes : If I add the following code to the Main method of an old Con...
public abstract class ModelBase { public Guid Id { get ; set ; } } public class User : ModelBase { public string Username { get ; set ; } } public abstract class ModelBaseConfiguration < T > where T : ModelBase { public virtual void Configure ( ) { ConfigureGuidProperty ( e = > e.Id ) ; } protected void ConfigureGuidPr...
Peculiar Issue When Using Expressions and ( Web ) Console Application
C#
why can we have a static circular reference in struct but not a instance type circular reference ?
struct C { //following line is not allowed . Compile time error . // it 's a non static circular reference . public C c1 ; //But this line compiles fine . //static circular reference . public static C c2 ; }
Why is Circular reference in struct of instance type not allowed but circular reference of static type allowed ?
C#
I have this model class : Then I add a few records in the database : Then I run this query : And I get : user2 Collection2 user1Why in Collection2 do I have a record ? And how to fix it ? UPDATE.This is a link to the test project https : //drive.google.com/file/d/0BxP-1gZwSGL5S1c4cWN1Q2NsYVU/view
public class User { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < User > Collection1 { get ; set ; } = new List < User > ( ) ; public virtual ICollection < User > Collection2 { get ; set ; } = new List < User > ( ) ; } var context = new UsersContext ( ) ; var user1 = new ...
Strange behavior of Entity Framework
C#
I have a variable of type Func < dynamic > and I am trying to assign it a value . If I assign it to a method that returns a value type ( e.g . int ) , I get the error 'int MethodName ( ) ' has the wrong return typeIf I wrap the method in a lambda call , however , it works fine . Also methods that return reference types...
private string Test ( ) { return `` '' ; } private int Test2 ( ) { return 0 ; } Func < dynamic > f = Test ; // WorksFunc < dynamic > g = Test2 ; // Does notFunc < dynamic > h = ( ) = > Test2 ( ) ; // Works
Ca n't assign methods that return value types to Func < dynamic >
C#
The problem is after running Temp totals is an IEnumerable that contains a IEnumerable of a simple class of The idea is to then take this data and group it into a dictionary so that i can get a total of all of the amounts with the key being the type.The end result should look like : I know that I could just foreach it ...
reportData = dbContext.FinancialsBySupplierAuditPeriodStatusType .Where ( v = > v.ReviewPeriodID == reportFilter.ReviewPeriodID & & v.StatusCategoryID == reportFilter.StatusCategoryID ) .GroupBy ( s = > new { s.SupplierID } ) .Select ( g = > new DrilldownReportItem { SupplierID = g.Key.SupplierID , SupplierName = g.Max...
Turning an IEnumerable of IEnumerables into a dictionary
C#
Let 's say I have a following C # interface : And SomeClass is defined as follows : Now I 'd like to define the implementation of the interface , which wo n't compile : before I change it to : Would n't it make sense that the type constraints are also `` inherited '' ( not the right word , I know ) from the interface ?
public interface IInterface < T > where T : SomeClass { void InterfaceMethod ( ) ; } public class SomeClass { public void SomeMethod ( ) ; } public class InterfaceImpl < T > : IInterface < T > { public void InterfaceMethod ( ) { T test = default ( T ) ; test.SomeMethod ( ) ; //Gives Error } } public class InterfaceImpl...
Why does a generic class implementing a generic interface with type constraints need to repeat these constraints ?
C#
I have some values . I want to run the shift for 6 days . but after each 2 days Shift id 1 rotate to shift id 2 and again after two days shift id 2 rotate to shift id 1 and so on ... My output should be likeI am getting shift id through a foreach loop . I tried like below mentioned way but not getting a proper resul . ...
DateTime date=04/03/2015 ( date ) Total Woring days=6 ( total ) Rotation Days=2 ( rotationday ) Shift Group=S1 ( this group contain two shift id 1 and 2 ) 04/03/2015=105/03/2015=106/03/2015=207/03/2015=208/03/2015=109/03/2015=1 SqlCommand cmd2 = new SqlCommand ( `` select ShiftID from ShiftGroup where ShiftName= ' '' +...
How to iterate date in for loop ?
C#
I 'm attempting to parse key-value pairs from strings which look suspiciously like markup using .Net Core 2.1.Considering the sample Program.cs file below ... My Questions Are:1.How can I write the pattern kvp to behave as `` Key and Value if exists '' instead of `` Key or Value '' as it currently behaves ? For example...
=============================input = < tag KEY1= '' vAl1 '' > -- -- -- -- -- -- -- -- -- -- kvp [ 0 ] = KEY1 key = KEY1 value = -- -- -- -- -- -- -- -- -- -- kvp [ 1 ] = vAl1 key = value = vAl1============================= =============================input = < tag KEY1= '' vAl1 '' > -- -- -- -- -- -- -- -- -- -- kvp [...
.Net Core Regular Expressions , Named groups , nested groups , backreferences and lazy qualifier
C#
Hi guys I wrote a simple program that split a string in the argument into number , letter and operators , however I come across that 23x+3=8I found the output is separate into each char 2 and 3 i want to have 23 as a whole number . is there way to push 2 number together ?
foreach ( char x in args [ i ] ) { if ( char.IsNumber ( x ) ) { inter [ i ] = Convert.ToInt32 ( x ) ; Console.WriteLine ( `` { 0 } is a number `` , x ) ; } else if ( char.IsLetter ( x ) ) { apha [ i ] = x ; Console.WriteLine ( `` { 0 } is a Letter `` , x ) ; } else if ( char.IsSymbol ( x ) ) { symbol [ i ] = x ; Consol...
Separate int and char and making whole number
C#
I am reading Concurrency in C # by Stephen Cleary in which there is an example that has puzzled me for a while . Normally the LINQ Select method requires a lambda method that returns the value for the result collection.In the book on page 30 there is an example where the lambda does n't return anything , but neverthele...
static async Task < int > DelayAndReturnAsync ( int val ) { await Task.Delay ( TimeSpan.FromSeconds ( val ) ) ; return val ; } static async Task ProcessTasksAsync ( ) { // Create a sequence of tasks Task < int > taskA = DelayAndReturnAsync ( 2 ) ; Task < int > taskB = DelayAndReturnAsync ( 3 ) ; Task < int > taskC = De...
Why does n't an async LINQ Select lambda require a return value
C#
When going over the project source code , I stumbled upon a method and wondered about one thing . Are the following two methods EXACTLY same from the performance/memory/compiler point of view ? Is the return variable automatically created by compiler ?
public static string Foo ( string inputVar ) { string bar = DoSomething ( inputVar ) ; return bar ; } public static string Foo ( string inputVar ) { return DoSomething ( inputVar ) ; }
Is return variable automatically created by compiler ?
C#
Scenario : I 'm trying to use Roslyn to merge a set of C # source fragments into a single code fragment.Issue : when parsing different classes with a leading comment , the comment above the first class ( SomeClass in the example ) is not preserved . For the second class ( AnotherClass ) , the comment IS preserved ... T...
using Microsoft.CodeAnalysis ; using Microsoft.CodeAnalysis.CSharp ; using Microsoft.CodeAnalysis.CSharp.Syntax ; using System.Collections.Generic ; using System.Diagnostics ; using System ; namespace roslyn01 { class Program { static void Main ( string [ ] args ) { var input = new [ ] { `` // some comment\r\nclass Som...
merging C # code with roslyn : comment disappears
C#
I was following the guidelines by MSDN . Two questions : Have I correctly implemented the equals method ? Could someone show me how to implement GetHashCode Correctly for my class ? MSDN does x ^ y , but I ca n't do it for mine .
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Crystal_Message { class Person { private string firstName = '' '' ; private string lastName= `` '' ; private string phone= '' '' ; public Person ( string firstName , string lastName , strin...
C # Implementing the Equals Method Correctly and How do I implement the GetHashCode Method
C#
I have two classes , BaseClass and Person . The Person class inherits from BaseClass . I then use the following generic method.Within the BaseClass I have a method , that invokes GetPropertyI then call this method from a unit test.When typeof ( T ) is used , BaseClass is returned . If I use item.GetType ( ) then Person...
public static PropertyInfo GetProperty < T > ( T item , Func < PropertyInfo , bool > predicate ) { return GetProperty ( typeof ( T ) , predicate ) ; } public class BaseClass { public void DoSomething ( ) { var property = GetProperty ( new Person ( ) , ( property ) = > p.Name == `` Name '' ) ; } } var person = new Perso...
Why is generic type not the correct type ?
C#
ExampleI call the inherited ClassB constructor . I pass in a null . ToLower ( ) throws an exception on a null . I want to check for a null before that happens . How can I do this ?
public class ClassA { public ClassA ( string someString ) { } } public class ClassB : ClassA { public ClassB ( string someString ) : base ( someString.ToLower ( ) ) { } }
How do I do operations on an inherited base constructor in C # ?
C#
what is the use of declaring like this to declare a private variablenow normally in the coding we use ID directly which in turn access the _ID which is private.How this offers more security instead of directly declaring as
private Int64 _ID ; public Int64 ID { get { return _ID ; } set { _ID = value ; } } ; public int64 ID { get ; set ; }
Private variable accessing
C#
I 'm trying out Roslyn 's code-generation capabilities using LinqPad to run fragments . LinqPad 's .Dump ( ) extension method renders a formatted view of the object to the Result pane.The code generated by http : //roslynquoter.azurewebsites.net/ includes a lot of code that does n't seem to do much other than add bloat...
using Microsoft.CodeAnalysis ; using Microsoft.CodeAnalysis.CSharp ; using Microsoft.CodeAnalysis.CSharp.Syntax ; var syn = SyntaxFactory.ReturnStatement ( SyntaxFactory.LiteralExpression ( SyntaxKind.NullLiteralExpression ) // .WithToken ( SyntaxFactory.Token ( SyntaxKind.NullKeyword ) ) ) // .WithReturnKeyword ( // S...
Are Roslyn 's `` .WithFooToken ( ) '' calls superfluous ?
C#
Given the following code packing four byte values into a uint.Is it possible to apply mathematical operators like * , + , / and - on the value in a manner that it can be unpacked into the correct byte equivalent ? EDIT.To clarify , if I attempt to multiply the value by another packed valueThen unpack using the followin...
private static void Pack ( byte x , byte y , byte z , byte w ) { this.PackedValue = ( uint ) x | ( ( uint ) y < < 8 ) | ( ( uint ) z < < 16 ) | ( ( uint ) w < < 24 ) ; } uint result = this.PackedValue * other.PackedValue public byte [ ] ToBytes ( ) { return new [ ] { ( byte ) ( this.PackedValue & 0xFF ) , ( byte ) ( ( ...
Mathematical operations on packed numerical values
C#
I have this code : it outputs me : But , I thought it should be : Because Baz is overriding the method . What is happening here ? Am I missing something ? Why did the output for fooBaz.Test ( ) is `` Foo '' instead of `` Baz '' ?
using System ; namespace Test { class Program { static void Main ( string [ ] args ) { Foo foo = new Foo ( ) ; Bar bar = new Bar ( ) ; Baz baz = new Baz ( ) ; Foo fooBar = new Bar ( ) ; Foo fooBaz = new Baz ( ) ; Bar barBaz = new Baz ( ) ; foo.Test ( ) ; bar.Test ( ) ; baz.Test ( ) ; fooBar.Test ( ) ; fooBaz.Test ( ) ;...
c # 6 bug ? virtual new method strange behavior
C#
Let 's assume , that we have the following classes : All of these classes are actually a lot longer , but also similar in the same degree . Is there a ( nice ) way of converting them all to one generic class ? The core problem is the line : because C # disallows calling parametrized ctors on generic class specializatio...
class ViewModelA { private ProxyA proxy ; public ViewModelA ( DataA data ) { proxy = new ProxyA ( data ) ; } public void DoSth ( ) { proxy.DoSth ( ) ; } public ProxyA Proxy { get { return proxy ; } } } class ViewModelB { private ProxyB proxy ; public ViewModelB ( DataB data ) { proxy = new ProxyB ( data ) ; } public vo...
Refactoring with generics
C#
I am looking at some covariance/contravariance stuff , I have a much wider question but it all boils down to this : This does n't work , even though BaseEntity is the parent abstract class of ProductStyle , is there a way of achieving this ?
GenericRepository < BaseEntity > repo = new GenericRepository < ProductStyle > ( context ) ;
Generics - Using parent class to specify type in generics
C#
I am having trouble with this , as I have difficulty properly formulating it too . Making it harder to google it . I will try to explain as clearly as possible . I 've simplified the code to make it clearer what my question isI have an abstract class that has methods and properties that are used by all clases that have...
public abstract class TheBaseClass { //some properties here public enum MyEnum { } // this one every class has . It is pretty much empty here . Not sure if this is best practice . //some methods here } public SpecializedClass : TheBaseClass { //some more properties here public new enum MyEnum { } //every single class h...
How to refer to an enum in the actual class rather than the base class in C #