lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
The following code snippet is extracted from Example 10-11 ( p. 343 ) from Programming C # 5.0 : I ca n't figure out how it could get compiled without exposing any information on T by applying constraints on it . Specifically , how could the compiler know how many bytes to allocate for the array , given that T may not ...
public static T [ ] Select < T > ( this CultureInfo [ ] cultures , Func < CultureInfo , T > map ) { var result = new T [ cultures.Length ] ; for ( int i = 0 ; i < cultures.Length ; ++i ) { result [ i ] = map ( cultures [ i ] ) ; } return result ; }
Why should the generic code compile without constraining T ?
C#
How can i get |ADT^A05| out of `` MSH|^~\ & |PHTADT09|ABC|DADIST00|ABC|20120425152829|rcalini1|ADT^A05|20429208851634|P|2.1|560 '' I have tried this but not working
`` | ( [ A-Z ] { 3 } ) ^ ( [ A-Z ] { 1 } ) ( [ 0-9 ] { 2 } ) | ''
regex get a match
C#
Consider this example : How do I know if calling await BarB ( ) changes the context without reading the body of the async Task BarB ( ) function ? Do I really need to know exactly whether an async function calls ConfigureAwait ( false ) at any point ? Or maybe the example is wrong and there 's no exception ?
async Task Foo ( ) { button.Text = `` This is the UI context ! `` ; await BarA ( ) ; button.Text = `` This is still the UI context ! `` ; await BarB ( ) ; button.Text = `` Oh no ! `` ; // exception ( ? ) } async Task BarA ( ) { await Calculations ( ) ; } async Task BarB ( ) { await Calculations ( ) .ConfigureAwait ( fa...
How do I know if an async method call changes the caller 's context ?
C#
I 'm tying to find characters from given list for each word of string separately , but I ca n't figure out how in my case to get found character by order exist in word and keep repeated characters . For example , if list to find is : var findChar = new List < string > { `` a '' , `` i '' , `` t '' , `` e '' , `` c '' }...
using System ; using System.Collections.Generic ; using System.Linq ; namespace _01_WORKFILE { class Program { static void Main ( string [ ] args ) { var findChar = new List < string > { `` a '' , `` i '' , `` t '' , `` e '' , `` c '' } ; List < string > displist = findChar ; Console.WriteLine ( `` Search for chars : [...
How to get found characters by order from string and keep duplicates to add it to the list without overwriting of previous
C#
I was looking at some code that I am refactoring and notices the try ... catch code wraps quite a lot of code , not of all which would throw `` normal '' exceptions i.e . The code would n't throw at all or if it did it would be totally fatal exceptions like out of memory exceptions . What I am wondering now is whether ...
try { // Wo n't throw ( I think that is the case anyway ! ) if ( e.Error == null ) { return ; } // Only fatal exceptions myClass c = new myClass ( ) ; // Now carry out the code that could cause catchable exception } catch { }
Is try wrapping excess code acceptable ?
C#
I am trying to implement Searching for a custom element in a list with a custom column name using a webservice for JQgrid , but I am out of ideas I would appreciate any help on this.I ca n't copy my code here but , for example , I have an entity like : and I created a function to return a list of this class : and from ...
public class Test { public int ID { get ; set ; } public string Name { get ; set ; } public string Nationality { get ; set ; } } public static List < Test > getList ( ) { List < Test > testList = new List < Test > ( ) ; Test testList1 = new Test ( ) ; testList1.ID = 123 ; testList1.Name = `` asd '' ; testList1.National...
select an element from a custom column from a list
C#
Ok , I need to test if two IEnumerable < T > are equal . The order of the elements is important , which means that : I 've seen a few answers on this site explaining how to do this with linq : for example , hereThe problem is that I have to repeatedly test for equality of pretty big collections ( thousands of elements ...
{ 1 , 2 , 4 , 1 , 3 } and { 1 , 2 , 1 , 3 , 4 } should not be equal . public static bool IsEqualTo < T > ( this IEnumerable < T > inner , IEnumerable < T > other ) where T : IEquatable < T > { if ( inner == null ) throw new ArgumentNullException ( ) ; if ( object.ReferenceEquals ( inner , other ) ) return true ; if ( o...
Algorithm for testing inequality of ordered large collections
C#
Considering the Method Declaration Like this : And then Calling it like this : What is the effect of @ before the method name ? Does it behave like putting it before a string which contains escaped characters ?
public void MethodName ( string param ) { // method body } obj . @ MethodName ( `` some string '' ) ;
Usage of @ Before Method Call
C#
To order a list with Linq we have to call OrderBy first en call ThenBy on the result for subordinate orderings.I 'm in a situation now where I do not know the top level ordering before hand . I have a list of of orderings which should be applied conditionally.Like this : So the list will always be ordered by Item1 , an...
var list = new List < Tuple < int , string , DateTime > > ( ) ; list.Add ( new Tuple < int , string , DateTime > ( 1 , `` B '' , new DateTime ( 2020 , 1 , 1 ) ) ) ; list.Add ( new Tuple < int , string , DateTime > ( 2 , `` A '' , new DateTime ( 2000 , 1 , 1 ) ) ) ; list.Add ( new Tuple < int , string , DateTime > ( 3 ,...
order list where top level order is unknown
C#
This is the obvious , easiest way to solve this problem . However , I 'd prefer not to use an unsafe method if I can avoid it . Basically , I have a bunch of integers which represent registers . There are assembly instructions that take register mnemonics as arguments . I 'd prefer not to have the logic to determine wh...
... { int *r1 , *r2 ; r1 = GetCorrectRegister ( first ) ; r2 = GetCorrectRegister ( second ) ; switch ( ( OpCode ) current.opcode ) { case OpCode.ADDR : r2 = r1 + r2 ; break ; } } ...
Safe ( in the C # sense ) way to implement something with pointers
C#
I have five paragraphs on my front end as below : In JS I wrote the following : I know when I click on the button it hides all the p tags , so it would be great if any one can tell me how I would be able to hide the third paragraph only .
< form id= '' form1 '' runat= '' server '' > < div id= '' div '' > < p > para1 < /p > < p > para2 < /p > < p > para3 < /p > < p > para4 < /p > < p > para5 < /p > < asp : Button id= '' button '' runat= '' server '' Text= '' Click to hide para3 ! '' / > < /div > < /form > $ ( `` # button '' ) .click ( function ( ) { $ ( ...
Hide the 3rd paragraph out of 5 paragraphs on a click of a button , with out assigning any class or id to the paragraphs
C#
Here is some sample data : Background : The above uses a simplified version of a Book class . It would , of course , contain many fields . My end goal is to allow the user to perform an 'advanced ' search allowing the user to specify any field and further allow the user to specify keywords using boolean algebra for a p...
List < Book > books = new List < Book > ( ) { new Book ( ) { Title = `` artemis fowl : the time paradox '' , Pages = 380 } , new Book ( ) { Title = `` the lieutenant '' , Pages = 258 } , new Book ( ) { Title = `` the wheel of time '' , Pages = 1032 } , new Book ( ) { Title = `` ender 's game '' , Pages = 404 } , new Bo...
Why do these three pieces of LINQ code produce different ( or erroneous ) results ?
C#
I 'm wondering if I do something like this : Is this going to work ? By `` work '' I mean - will MethodA be unsubscribed from ExternalObject.Click event ? And other related questions : What happens behind the scenes when an instance method is used instead of delegate instance ? ( like above ) Does this cause implicit c...
class A { public MethodA ( ) { } public MethodB ( ) { ExternalObject.Click += this.MethodA ; } public MethodC ( ) { ExternalObject.Click -= this.MethodA ; } } A a = new A ( ) ; a.MethodB ( ) ; a.MethodC ( ) ;
C # events and class methods
C#
I have a database called ebookstore.db as below : and JSON as below : I want when slug on JSON is not the same as a title in the database , it will display the amount of data with a slug on JSON which is not same as a title in the database in ukomikText.Code : BukuUpdate.cs : I have a problem , that is when checking sl...
string judulbuku ; try { string urlPath1 = `` https : // ... '' ; var httpClient1 = new HttpClient ( new HttpClientHandler ( ) ) ; httpClient1.DefaultRequestHeaders.TryAddWithoutValidation ( `` KIAT-API-KEY '' , `` ... . '' ) ; var values1 = new List < KeyValuePair < string , string > > { new KeyValuePair < string , st...
UWP - Compare data on JSON and database
C#
I am trying to mask a string name with * ( asterisks ) and exclude both the first and nth ( 5th ) characters.Example : UserFirstName - > U****F*******I managed to exclude the first character with ( ? ! ^ ) . : output : UserFirstName - > U************How can I also exclude the character in the 5th position ?
var regex = new Regex ( `` ( ? ! ^ ) . `` ) ; var result = regex.Replace ( stringUserName , `` * '' ) ;
Regex Replace exclude first and nth character
C#
I 'm doing a big refactor of a pile of code that used to use a bunch of multidimensional arrays that were constantly getting resized . I created a data object to replace the 2D array , and I 'm now passing a list of these around.I discovered something that worries me a little though . Let 's say I have some code that l...
List < NCPoint > basePoints = new List < NCPoint > ( ) ; // ... snip populating basePoints with starting dataList < NCPoint > newPoints = TransformPoints ( basePoints , 1 , 2 , 3 ) ; public List < NCPoint > TransformPoints ( List < NCPoint > points , int foo , int bar , int baz ) { foreach ( NCPoint p in points ) { poi...
Passing Collections Immutably
C#
Today I see this code : And I can not understand . `` ~ '' - This is a mistake ? As far as I remember , `` ~ '' is placed before the destructors . But this is enum . And this code compiled !
ViewBag.country = from p in CultureInfo.GetCultures ( CultureTypes.AllCultures & ~CultureTypes.NeutralCultures ) select new SelectListItem { Text = p.EnglishName , Value = p.DisplayName } ;
What does `` ~ '' mean before enums
C#
If I were to change the value of bool.TrueString , I 'd do it using Reflection : However , I can not manage to change the value of , say , Type.Delimiter : Why is this ?
typeof ( bool ) .GetField ( `` TrueString '' , BindingFlags.Public | BindingFlags.Static ) .SetValue ( null , `` Yes '' ) ; Console.WriteLine ( bool.TrueString ) ; // Outputs `` Yes '' typeof ( Type ) .GetField ( `` Delimiter '' , BindingFlags.Public | BindingFlags.Static ) .SetValue ( null , '- ' ) ; Console.WriteLine...
Why ca n't I change Type.Delimiter using Reflection ?
C#
I have never done this before , and while I ca n't think of a specific reason that it would break , I 'd like to verify that it is valid to use an out variable as follows :
void Main ( ) { var types = new [ ] { typeof ( A ) , typeof ( B ) } ; bool b = false ; var q = from type in types from property in type.GetProperties ( ) let propertyName = GetName ( property , out b ) select new { TypeName = type.Name , PropertyName = propertyName , PropertyType = property.PropertyType.Name , IsNullab...
Is it safe to use out variables in calls within LINQ statements ?
C#
I am looking at some code that a coworker wrote and what I expected to happen is n't . Here is the code : In another class , I would have expected to be able to do : and it reference the same Instance of that class . What happens is I can only have one .Instance . Something that I did not expect . If the Instance prope...
public class SingletonClass { private static readonly SingletonClass _instance = new SingletonClass ( ) ; public static SingletonClass Instance { get { return _instance ; } } private SingletonClass ( ) { //non static properties are set here this.connectionString = `` bla '' this.created = System.DateTime.Now ; } } priv...
Trying to understand how static is working in this case
C#
I have recently found an interesting behavior of C # compiler . Imagine an interface like this : Now if we do The compiler will complain that he does not know which overload to chose ( Ambiguous invocation ... ) . Seems logical , but when you try to do this : It will suddenly have no troubles figuring out that null is ...
public interface ILogger { void Info ( string operation , string details = null ) ; void Info ( string operation , object details = null ) ; } logger.Info ( `` Create '' ) logger.Info ( `` Create '' , null )
Strange C # compiler behavior when choosing overload that looks like a bug/missing feature
C#
I have a base class and several derived classes ( for example Base and ChildA : Base ) . Each time I create an instance of ChildA class , I want it to be assigned a unique instance number ( similar to autoincrement IDs in relational databases , but for my classes in memory as opposed to in a database ) .My question is ...
ChildA,5ChildB,6ChildC,9
BaseClass with instance counter
C#
I have a Question for you guys.I have 2 unit tests which are calling webservices .The value that one unit-test returns should be used for another unit test methodExample How can i store a value in one unittest and use that value in another unittest .
namespace TestProject1 { public class UnitTest1 { String TID = string.empty ; public void test1 { //calling webservices and code Assert.AreNotEqual ( HoID , hID ) ; TID = hID ; } public void test2 { //calling webservices and code string HID = TID // I need the TID value from the Above testcase here Assert.AreNotEqual (...
Holding a Value in Unit tests
C#
I ca n't change this `` value '' variable from locals or immediate window.Whats wrong ? T is n't a int in runtime ? i ca n't change _value too.I think this is a bug or something ? Beside using this , tried to use instance of Just , worked fine
class Program { static void Main ( string [ ] args ) { Just < int > just = new Just < int > ( ) ; just.Try ( 5 ) ; } } class Just < T > { private T _value ; public void Try ( T value ) { this._value = value ; } }
Changing T type int in local window
C#
I have a base class , say named B. I have two derived classes , D1 and D2.Looks like : Now , I created a new interface IDeepCopyable < T > which has one method Clone ( ) : I want to force each subclass too implement this interface with the base class ( i.e . IDeepCopyable < B > .If I try to leave B 's declaration as-is...
public abstract class B { public abstract void DoSomething ( ) ; } public class D1 : B { public override void DoSomething ( ) { ... } } public class D2 : B { public override void DoSomething ( ) { ... } } public interface IDeepCopyable < T > { T Clone ( ) ; } public abstract class B : IDeepCopyable < B >
Can I Enforce a Subclass to Implement an Interface ?
C#
In .NET , I understand that there is a garbage collector that will manage the memory that 's being used during the execution of a program . This means that objects will be cleaned up when they go unused.I was wondering if I could keep a static counter in a certain class that automatically updates when instances of that...
public class CountableInstance { public static int total = 0 ; public CountableInstance ( ) { InstanceIndex = total ; total++ ; // Next instance will have an increased InstanceIndex } public CountableInstance ( ... ) : this ( ) { // Constructor logic goes here } public int InstanceIndex { get ; private set ; } }
Is is possible to keep track of the current number of instances of a class ?
C#
I recently wrote a class library that includes some objects that model certain types of files . For example , there is an abstract Document class , with derived classes PdfDocument ( concrete ) and OfficeDocument ( abstract , with concrete derived classes such as WordDocument and ExcelDocument ) , etc.Currently the way...
var wordDocument = new WordDocument ( wordDocumentByteArray ) ; var pdfDocument = new PdfDocument ( pdfDocumentByteArray ) ; var wordDocument = DocumentFactory.GetDocument ( wordDocumentByteArray , `` docx '' ) ; // pass file extension so we know what the file is
Who should be responsible for selecting the appropriate derived class ?
C#
I 'm working on rewriting an MVC application that currently utilizes cookies to hold data between multiple pages such as a date . I have tried to come up with an option that would hold the data in the controller by using something like this : The problem that I 'm facing is that this is overwritten on each page load . ...
public DateTime HoldDate { get ; set ; }
Holding value between multiple pages
C#
I have an enum type which derives from byte . In my common library , at some point there is a cast of an enum parameter to int.The problem is when my byte derived enum gets to that method in the common library , the cast to int fails and raises an exception.Is there a way to type check an enum 's base class so I can do...
enum DaysByte : byte { Sat = 1 , Sun , Mon , Tue , Wed , Thu , Fri } ; enum DaysInt : int { Sat = 1 , Sun , Mon , Tue , Wed , Thu , Fri } ;
How to Type check for enum instance base class ?
C#
Basically I have a list of objects . Let 's call them meetings . Inside the meetings there is another list of objects . Let 's call those participants . I want to return all meetings where a certain participant is in the list.I want something like this : Basically return a list of meetings , where the meeting has a par...
meetings.Where ( meeting = > meeting.Participants.Name == `` Test name '' ) .ToList ( ) ;
Extract list where string is contained inside a list inside the list
C#
The following query does solve my problem however it seems overly complex.The problem is I have a table that stores menu options ( id , name , description and price ) . I also have a session variable that stores the users selections in a Dictionary ( storing id and quantity ) .The LINQ I 've produced below basically ca...
var prices = _db.MenuOptions .Select ( o = > new { o.Id , o.Price } ) .ToDictionary ( o = > o.Id , o = > o.Price ) ; Session [ `` price '' ] = prices .Where ( p = > orderItems.Keys.Contains ( ( int ) p.Key ) ) .Sum ( p = > p.Value * orderItems [ p.Key ] ) ;
How to improve my LINQ
C#
i 'm trying to make this code works in async way , but i got some doubts.I got some string input collection , and i would like to run this method on them.Then i would do Task.WhenAll , and filter for non empty strings.But it wo n't be async as inside the method i 'm already awaiting for the result right ?
public async Task < string > GetAsync ( string inputA , string inputB ) { var result = await AnotherGetAsync ( inputA , inputB ) .ConfigureAwait ( false ) ; return result.Enabled ? inputB : string.Empty ; }
C # TaskWhenAll on method which is returing result depending on awaited call
C#
If I have made a variable of a non-reference type , say int , nullable , i.e . int ? , does this mean I need to use a constructor before assigning a value ? Normally to intialise a non-reference type variable I simply doBut if I have a nullable non-reference data type variable is initialisation neccessary , as below , ...
int foo = 5 ; int ? foo = new int ( ) ; foo = 5 ;
Is new ( ) required for nullable non-reference type variable ?
C#
I have a somewhat complicated Class that may or may not contain a list of items of the same typeThe class itself is serializeable , however its going to be a giant waste of space to serialize the objects in the list since they are serialized and added to the database prior to being included in the list.Is there a way t...
Class Items { List < Items > SubItems ... }
Specify how to Serialize my object if it is in a list
C#
Consider this : ... and this : The first example compiles , the second does n't . To use a nested type reference when inheriting from a generic type I must qualify it with the parent 's type name : My question is , why ? and why does n't this restriction apply when referring from an attribute in the parent type ( first...
[ SomeAttr ( typeof ( Bar ) ) ] class Foo { class Bar { } } class Foo : ISomething < Bar > { class Bar { } } class Foo : ISomething < Foo.Bar > { class Bar { } }
Why do I have to parent-type-qualify to use a nested type when inheriting from a generic type ?
C#
If I have a string variable with value as follows : -and I want to manipulate this string and make it as follows : -ie I want to just remove all the duplicates in it , how should I do it ? Please help . Thanks .
string mystring = `` TYPE1 , TYPE1 , TYPE2 , TYPE2 , TYPE3 , TYPE3 , TYPE4 , TYPE4 '' ; string mystring = `` TYPE1 , TYPE2 , TYPE3 , TYPE4 '' ;
Manipulate string problem
C#
Why does the code below display ' ? ' instead of ' $ ' ? The result is : 29,56 ?
static void Main ( string [ ] args ) { float price = 29.56f ; Console.WriteLine ( price.ToString ( `` c '' ) ) ; }
Why is the currency modifier `` C '' returning ' ? ' instead of ' $ ' in C # ?
C#
This is a rather educational , out of curiosity question . Consider the following snippet : Where SubscribeDebug subscribes a simple observer : The output of this is : Value : 0Value : 1Value : 2Value : 3Value : 4And then blocks . Can someone help me understand the underlying reason why it happens and why the observabl...
var enumerable = Enumerable.Range ( 0 , 5 ) ; var observable = enumerable.ToObservable ( ) ; var enu = observable.Concat ( observable ) .ToEnumerable ( ) ; enu.ToObservable ( ) .SubscribeDebug ( ) ; public class DebugObserver < T > : IObserver < T > { public void OnCompleted ( ) { Debug.WriteLine ( `` Completed '' ) ; ...
Why does repeated Enumerable to Observable conversion block
C#
Hi I am new to C # and have been learning it . Actually think I am getting use to it there are a few things which I am unsure about but will try to research them before asking . That said one thing I can not find it collections . I come from a VB.NET back ground and previously I used collections of another class to sto...
Public class UserDetails Public Property Username ( ) As String Get Return sUsername End Get Set ( ByVal value As String ) sUsername = value End Set End Property Public Property Forename ( ) As String Get Return sForename End Get Set ( ByVal value As String ) sForename = value End Set End Property Public Property Surna...
Collections in C # over VB.NET
C#
I have an XML document from which I need to extract a nodeset and add a namespace . So , from a doc I extract this : and need to create this : There will be a variable quantity of list items and the elements might change and have different name , so I need a generic solution.Is there an easy way to do that in .Net C # ...
< List > < ListItem > < SomeData > Here is some text < /SomeText > < /ListItem > < ListItem > < SomeData > Here is some more text < /SomeText > < /ListItem > < /List > < my : List xmlsns : my='http : //SomeNamespace.org > < my : ListItem > < my : SomeData > Here is some text < /my : SomeText > < /my : ListItem > < my :...
Changing XML using .Net
C#
I 'm building the following class : What I need is to make T be the type of child Foo class : Is it achievable ? If so , how ?
abstract class Foo { protected abstract void Process ( FooProcessor < T > processor ) } class FooChild : Foo { protected override void Process ( FooProcessor < FooChild > processor ) { } }
Self generic type
C#
I am experiencing a weird behaviour from Visual Studio 2013 . I 've got a C # program which writes to the standard output , let 's sayIn the Debug tab of the project 's properties I have redirected the output to a file , like this : If I open the file within those 10s when my application is still running , the file doe...
using System ; using System.Threading ; namespace CsSandbox { class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` Hello world ! `` ) ; Thread.Sleep ( 10000 ) ; } } }
Visual Studio clears output file at end of debugging
C#
Essentially what I want to do is impliment a class that can contain a list of references to instances of the same type . Something like the following : I know this wo n't compile because the interface explicitly says my Settings must be of the type List < IAccessibilityFeature > . What I am after is some guidance as to...
interface IAccessibilityFeature { List < IAccessibilityFeature > Settings { get ; set ; } } class MyAccess : IAccessibilityFeature { List < MyAccess > Settings { get ; set ; } }
Can you define an interface such that a class that implements it must contain a member that is also of that class ?
C#
First of all “ A method group is a set of overloaded methods resulting from a member lookup ” . In my example I use the set of Console.WriteLine methods with 19 overloads.The definition of a method group in C # Language Specification also states that : “ A method group is permitted in an invocation-expression ( §7.6.5 ...
Action < string > print = ( Action < string > ) Console.WriteLine ; print ( `` Hello ! `` ) ; if ( Console.WriteLine is Action < string > ) { Console.WriteLine ( `` We 're compatible ! `` ) ; }
Why are the methods groups allowed on the left-side of ‘ is ’ operator and how can this be used in practice ?
C#
I 'm writing a method to generate a DataTable taking as datasource a generic IEnumerable . I am trying to set a default value on the field if theres no value , with the code below : It 's throwing this error : The type or namespace name 'typeAux ' , could not be found ( are you missing a using directive or an assembly ...
private void createTable < T > ( IEnumerable < T > MyCollection , DataTable tabela ) { Type tipo = typeof ( T ) ; foreach ( var item in tipo.GetFields ( ) ) { tabela.Columns.Add ( new DataColumn ( item.Name , item.FieldType ) ) ; } foreach ( Pessoa recordOnEnumerable in ListaPessoa.listaPessoas ) { DataRow linha = tabe...
Why is n't this code compiling ?
C#
We have a legacy .NET solution which has a combination of MVC and WebForms stuff , and some Web API projects as applications under the website root . Obviously these Web API applications will inherit the website 's web.config settings.We also have another project - a bounded context - for SSO authentication which sits ...
- wwwroot // .NET Framework - API 1 // .NET Framework - API 2 // .NET Framework - ... - SSO / authentication // bounded context , built in .NET Core < configSections > < section name= '' configBuilders '' ... / > < /configSections > < configBuilders > < builders > < add name= '' Secrets '' optional= '' false '' userSec...
Blocking web.config inheritance in a sub-application
C#
Below code compiles in VS2015.2 , but after upgrade to VS2015.3 it fails with error CS0019 : Operator '== ' can not be applied to operands of type 'Registration < Something > ' and 'Something'.I can not find any notice about such a change in the changelog for update 3 . Can someone tell me , why this happens ? And whic...
public class Class1 { public Class1 ( ) { var a = new Registration < Something > ( ) ; var x = a == Something.Bad ; // this line fails in VS2015.3 } } public struct Registration < T > where T : struct { public static implicit operator T ? ( Registration < T > registration ) { return null ; } } public enum Something { G...
Combination of implicit conversion , equality operator and nullables fails to compile after update from Visual Studio 2015.2 to 2015.3
C#
In the following code , are the using blocks redundant or are they necessay to fully release resources ?
using ( var dialog = new AboutBox ( ) ) dialog.ShowDialog ( ) ; using ( var form = new OptionForm ( ) ) form.Show ( ) ;
It is redundant to wrap dialogs in using blocks ?
C#
I am developing a software that takes realtime-data and extracts a number of features from that depending on user input . Each available feature consists of one method that takes an array of doubles and return the wanted feature , such as this one for the MeanAbsoluteValue : Since each of the features only has the one ...
public static class MeanAbsoluteValue { public static double Calculate ( double [ ] data ) { return data.Sum ( s = > Math.Abs ( s ) ) / data.Length ; } }
Declare static classes so that they can be stored within List
C#
sorry if this sounds noobish.I 'm trying to make a Quiz game on Unity by using C # and a database in SQL Server.In this part , i 'm trying to show the highest score so , i did a code to select the max in database : Then , i try to print the data in a UI text in this script : And it gives me this error : IndexOutOfRange...
public bool BuscarScoreFinal1 ( ) { SqlDataReader dataReader = null ; if ( RunQuery ( string.Format ( `` SELECT MAX ( PlayerScore1 ) FROM ScoreQuiz1 '' , tableScoreQuiz1 ) , ref dataReader ) ) { while ( dataReader.Read ( ) ) { id1 = dataReader.GetInt32 ( dataReader.GetOrdinal ( `` ID '' ) ) ; PlayerName1 = dataReader.G...
IndexOutOfRangeException while trying to select on database by C #
C#
The main reason I 'm using the BST is to get the Majority Element , being the Value > Array.Length / 2.So , if we have an array of 5 elements , there must be a minimum of at least 3 to be considered the majority.Now the problem I am facing at the moment is that the Majority Element is being chosen for whichever element...
public Node nnde ( Node root ) { if ( root== null ) { root= newNode ; size++ ; return root ; } if ( elm < root.elm ) { if ( root.lft ! = null ) { InsertNewNode ( root.lft , elm ) ; } else { root.lft = new Node ( elm ) ; } } else if ( elm > root.rght ) { if ( root.rght ! = null ) { InsertNewNode ( root.rght , elm ) ; } ...
C # Binary Search Tree giving Incorrect Majority Element
C#
Can I use type parameter as implementing specific interface at Runtime without Reflection ? The following pseudocode is what I want to do .
void Run1 < T > ( ) { // ... if ( typeof ( IEnumerable ) .IsAssignableFrom ( typeof ( T ) ) { Run2 < T implementing IEnumerable > ( ) ; // < - use T as implementing IEnumerable } // ... } void Run2 < T > ( ) where T : IEnumerable { // ... }
Is there a way to cast type parameter ?
C#
Why does the getter Val happen to simulate volatility for the field val ? I 'm assuming that leveraging a method call is not a reliable way to keep the variable volatile . ( To try it out , build for release and execute directly without the debugger . )
class Program { private int val = 0 ; public int Val { get { return val ; } } public static void Main ( ) { var example = new Program ( ) ; Task.Run ( ( ) = > example.val++ ) ; while ( example.val == 0 ) ; // Hangs if val is not volatile while ( example.Val == 0 ) ; // Never seems to hang } }
Why does a method call flush the nonvolatile variable 's value to the main thread ?
C#
I have a nested List as in the example : I want to merge all the lists having at least an element in common so that the output will be a List < List < int > > with elements : Thank you
List < List < int > > myList = new List < List < int > > ( ) ; myList.Add ( new List < int > { 2 , 7 , 3 } ) ; myList.Add ( new List < int > { 4 , 6 } ) ; myList.Add ( new List < int > { 2 , 5 , 1 } ) ; myList.Add ( new List < int > { 7 , 0 , 2 } ) ; myList.Add ( new List < int > { 4 , 9 } ) ; List < int > 2 , 7 , 3 , ...
Merge element of nested List in unique list c #
C#
Given the following class : What rules are applied to select one of its two generic methods ? For example , in the following code : it ends up calling EnumHelper.GetStrings < List < MyEnum > > ( List < MyEnum > ) ( i.e . Overload 1 ) , even though it seems just as valid to call EnumHelper.GetStrings < MyEnum > ( IEnume...
public static class EnumHelper { //Overload 1 public static List < string > GetStrings < TEnum > ( TEnum value ) { return EnumHelper < TEnum > .GetStrings ( value ) ; } //Overload 2 public static List < string > GetStrings < TEnum > ( IEnumerable < TEnum > value ) { return EnumHelper < TEnum > .GetStrings ( value ) ; }...
Why does n't the C # compiler consider this generic type inference ambiguous ?
C#
I have to create a method for selecting a firts property from collection with the specified type.I have created the method like this ( I have removed some parts for the brevity ) : And I can call this method as : Everything works fine.But , I do n't want to set first argument type as Person , because compiler can infer...
public static IQueryable < TResult > SelectFirstPropertyWithType < T , TResult > ( this IQueryable < T > source ) { // Get the first property which has the TResult type var propertyName = typeof ( T ) .GetProperties ( ) .Where ( x = > x.PropertyType == typeof ( TResult ) ) .Select ( x = > x.Name ) .FirstOrDefault ( ) ;...
Set only second argument type in generic method
C#
I 'm attempting to make a namespace for the first time while learning programming . I am hoping there is a way around the problem I 've run into that is n't particularly messy , but essentially I have a class object that keeps two dictionaries of two nested class objects . I need to be able to pass the Dictionary of Ne...
namespace MyFirstNamespace { public class BossClass { public Dictionary < int , NestedClassA > DictionaryA = new Dictionary < int , NestedClassA > ( ) ; public Dictionary < int , NestedClassB > DictionaryB = new Dictionary < int , NestedClassB > ( ) ; public class NestedClassA { ... arbitrary class definition ... } pub...
Getting the type of another nested class from the same `` parent '' class
C#
When there is no new ( ) constraint , I understand how it would work . The JIT Compiler sees T and if it 's a reference type makes uses the object versions of the code , and specializes for each value type case.How does it work if you have a new T ( ) in there ? Where does it look for ?
public T Foo < T , U > ( U thing ) where T : new ( ) { return new T ( ) ; }
C # - How do generics with the new ( ) constraint get machine code generated ?
C#
I got a struct with the following fieldsWhen I initialise it and check the memory size , I get size as 8.However , when I change the order as below and execute it , I get the size as 12.Ideally , it should be 7 bytes . However , from this link msdn I can understand that overhead allocation do happens . However , why is...
public struct Person { public int Age ; public short Id ; public byte Marks ; } Person instance = new Person { Age = 10 , Id = 1 , Marks = 75 } ; Console.WriteLine ( Marshal.SizeOf ( instance ) ) ; public struct Person { public byte Marks ; //1 byte public int Age ; //4 public short Id ; //2 }
Why the order of properties inside the Struct changes the size of instance ?
C#
I 'm using NLog like thisBut I want to see the exception when debugging . So I tried : Is there a neater way of doing that ?
try { // ... some code } catch ( AException ex ) { logger.ErrorException ( ex.Message , ex ) ; } # if ! DEBUG try { # endif // ... some code # if ! DEBUG } catch ( AException ex ) { logger.ErrorException ( ex.Message , ex ) ; } # endif
How to view exceptions when debugging ?
C#
I 've made an app that can access and control Onvif cameras which it does well enough . However this is my first time making any app that uses web requests like this ( or at all ) so I assume I 'm probably using quite basic techniques.The part of code I 'm curious about is this : The code works fine , however using the...
Uri uri = new Uri ( String.Format ( `` http : // '' + ipAddr + `` /onvif/ '' + `` { 0 } '' , Service ) ) ; WebRequest request = WebRequest.Create ( ( uri ) ) ; request.Method = `` POST '' ; byte [ ] b = Encoding.ASCII.GetBytes ( PostData ) ; request.ContentLength = b.Length ; //request.Timeout = 1000 ; Stream stream = ...
Ways of speeding up WebRequests ?
C#
Consider the following organization of classes : Since both the restaurants serve completely different sets of dishes , what will be the correct way ( design-wise ) to represent the type of dish in the interface ? Will it be a good design decision to define an Enum listing all the dishes -- Italian and Chinese -- as a ...
interface Restaurant { public void dine ( Object dish ) ; } class ItalianRestaurant implements Restaurant { public void dine ( Object dish ) { // eat with spoon and forks } } class ChineseRestaurant implements Restaurant { public void dine ( Object dish ) { // eat with chopsticks } }
Should the interface define implementation specific enum values ?
C#
I have a string which is 900-1000 characters long.the pattern string follows is `` Number : something , somestringNumber : something , somestring '' and so on example string : `` 23 : value , ordernew14 : valueagain , orderagain '' the requirement is whenever it crosses more than 1000 characters , I have to remove firs...
sortinfo = sortinfo.Remove ( 0 , 500 ) ; sortinfo = new string ( sortinfo.SkipWhile ( c = > ! char.IsDigit ( c ) ) .ToArray ( ) ) ; class Program { static void Main ( string [ ] args ) { string str ; str=TrimSortInfo ( `` 23 : value , ord4er24 : valueag4ain , order6again15 : value , order '' ) ; // breaking value //str...
Trim String value with particular pattern in C # .NET
C#
I have a custom Matrix class that I would like to implement a custom object initializer similar to what a double [ , ] can use but can not seem to figure out how to implement it . Ideally I would like to have it look like thisas of now I have a regular constructor with a signature of that accepts a call like thisand an...
var m1 = new Matrix { { 1.0 , 3.0 , 5.0 } , { 7.0 , 1.0 , 5.0 } } ; public Matrix ( double [ , ] inputArray ) { ... } var m1 = new Matrix ( new double [ , ] { { 1.0 , 3.0 , 5.0 } , { 7.0 , 1.0 , 5.0 } } ) ; var m2 = new Matrix { new [ ] { 1.0 , 3.0 , 5.0 } , new [ ] { 7.0 , 1.0 , 5.0 } } ;
How to implement a clean Custom Object Initializer for a Matrix class
C#
What I want to do is have a method that takes a generic type as a parameter with a constraint . However , the constraint 's type also has a second generic type , but I want the method to work regardless of what the second typing is : Specifically , I 'm trying to have my EventManager class receive any kind of event and...
public class IEvent < T > where T : EventArgs { } public class EventManager { public void DoMethod < T > ( ) where T : IEvent < ? ? ? > { } }
Generic methods with constraints that are generic
C#
I 'm a substantial way through developing a sizeable WPF application that will control a sophisticated piece of hardware via serial comms . At the very bottom of the application `` stack '' I have a serial comms tier ( utilising the .Net 'SerialPort ' class ) . Reading and writing to the h/w device is a fundamental par...
private async void SomeButtonClick ( object sender , EventArgs e ) { await Task.Run ( ( ) = > _someBLLService.TurnPumpOn ( ) ) ; } private async void SomeButtonClick ( object sender , EventArgs e ) { await _someBLLService.TurnPumpOn ( ) ; }
Should I use async `` all the way '' for my GUI app ?
C#
If I have a generic function that returns a T or some default value I want to use the ? ? operatorThis fails with the message Operator ' ? ? ' can not be applied to operands of type 'T ' and 'T ' I assume this is because T might not be nullable . But I would also assume that the ? ? operator above should do the same as...
T f < T > ( T a , T b ) { return a ? ? b ; } T f < T > ( T a , T b ) { var a_ = a ; return a_ ! = null ? a_ : b ; }
Why ca n't the ? ? -operator be applied to generic types , but a null-check can be applied ?
C#
I am trying to pass a view model with complex types to my controller . I have researched everything I can top to bottom over this subject and I am still confused . The Problem : When I click my submit button , the view model is passed in but the List of MacroInfo property is null.UpdateIndexViewModelMacroInfoController...
public class UpdateIndexViewModel { //This view model will become larger later public List < MacroInfo > MacrosToUpdate { get ; set ; } } public class MacroInfo { public bool IsSelected { get ; set ; } public string FullPath { get ; set ; } public string Id { get ; set ; } public DateTime CreatedAt { get ; set ; } } [ ...
View model with complex type is null when passed to controller
C#
How could be defined a code that store 'this ' during class finalization ? How the garbage collector should behave ( if defined somewhere ) ? In my mind the GC should finalize multiple times the class instance , and the following test application shall print `` 66 '' , but the finalizer is executed only once , causing ...
using System ; namespace Test { class Finalized { ~Finalized ( ) { Program.mFinalized = this ; } public int X = 5 ; } class Program { public static Finalized mFinalized = null ; static void Main ( string [ ] args ) { Finalized asd = new Finalized ( ) ; asd.X = 6 ; asd = null ; GC.Collect ( ) ; if ( mFinalized ! = null ...
Store 'this ' at finalization
C#
I have the following code : It gives me this output : How can I ensure that some local variables will be passed to the BeginInvoke method as expected ? Thanks in advance .
string message ; while ( balloonMessages.TryDequeue ( out message ) ) { Console.WriteLine ( `` Outside : { 0 } '' , message ) ; BeginInvoke ( ( MethodInvoker ) delegate ( ) { Console.WriteLine ( `` Inside : { 0 } '' , message ) ; } ) ; } Outside : some_messageInside :
How to ensure the correct state of local variables when using BeginInvoke method
C#
I was refactoring some the other day , I bumped into something like that : and ReSharper suggested to refactor it as : I am a bit skeptical , actually I am not sure when the implicit Dispose call will happen with the second version.How can I know ?
public async Task < Result > Handle ( CancelInitiatedCashoutCommand command , CancellationToken cancellationToken ) { using ( _logger.BeginScope ( `` { @ CancelCashoutCommand } '' , command ) ) { return await GetCashoutAsync ( command.CashoutId ) .Bind ( IsStatePending ) .Tap ( SetCancelledStateAsync ) .Tap ( _ = > _lo...
Refactoring : using statement without scope , when does the implicit ` Dispose ` call happen ?
C#
I 'm doing some reaserch on CIL optimizing techniques . I 've created this simple code : When I watch this code in disassembly window , I see something like : I understand that it put 10 into ecx , then used 63A96648 as a pointer to WriteLine ( ) function , but I 'm not sure why does it use the ecx register . I always ...
int Function ( ) { return 10 ; } // ( ... ) int Number = Function ( ) ; Console.WriteLine ( Number ) ; 00252DB0 mov ecx,0Ah 00252DB5 call 63A96648 00252DBA ret
Why does Console.WriteLine ( ) use ecx register , event though eax and ebx are free ?
C#
I got three classes ( classA , classB and classC ) that inherit from an interface 'IFoo ' ; if use this or it works just fine but other combinations wo n't even compile : orIt seems to me that in some cases the compiler implicitly unboxes the child classes to their IFoo interface but in some other cases do n't . What d...
var fooItem = ( request.classAitem ? ? ( request.classBitem as IFoo ? ? request.classCitem ) ) var fooItem = ( request.classAitem ? ? request.classBitem ? ? request.classCitem as IFoo ) var fooItem = ( request.classAitem as IFoo ? ? request.classBitem ? ? request.classCitem ) var fooItem = ( request.classAitem ? ? requ...
How null-coalsescing operator works
C#
I have an OSS project on GitHub being built against .NET 4.5 on AppVeyor CI with Visual Studio 2017 ( not the preview stuff , just 2017 ) .The solution builds a COM add-in that extends a famously dreaded legacy Win32 IDE , and we 've established that the earliest Windows version we need to run on , is Vista ( so , .net...
+ < ItemGroup > + < Analyzer Include= '' ..\RubberduckCodeAnalysis\RubberduckCodeAnalysis\bin\Release\netstandard1.3\RubberduckCodeAnalysis.dll '' / > + < /ItemGroup > +Project ( `` { 9A19103F-16F7-4668-BE54-9A1E7A4F7556 } '' ) = `` RubberduckCodeAnalysis '' , `` RubberduckCodeAnalysis\RubberduckCodeAnalysis\Rubberduck...
Can I have an analyzer on a .net 4.5 project ?
C#
In all examples I can find as well as the automatically generated code i Visual Studio , events are set using the following code : But I can also write it visually cleaner by omitting the constructor wrapper : Which also compile fine.What is the difference between these two ? And why is the first one mostly used/prefer...
button1.Click += new System.EventHandler ( this.button1_Click ) ; button1.Click += this.button1_Click ;
What the purpose/difference in using an event-type constructor
C#
I was running through some code the other day and found this line which I thought was peculiar.I ca n't understand why they are multiplying by int 20 , and then dividing by float 20.0My initial suspicion is that it had something to do with either rounding or precision , but I could n't find the answer on here or on Goo...
Math.Round ( 20 * ( bytes / 1024.0 / 1024.0 / 1024.0 ) , MidpointRounding.AwayFromZero ) / 20.0 ) ;
Is there a reason for mulitplying by an integer ' x ' , then dividing by that same ' x ' as a double ?
C#
How do I group `` adjacent '' Sites : Given data : I want result : I tried using GroupBy with a custom comparer function checking routeIds match and first site 's end milepost is equal to the next sites start milepost . My HashKey function just checks out routeId so all sites within a route will get binned together but...
List < Site > sites = new List < Site > { new Site { RouteId= '' A '' , StartMilepost=0.00m , EndMilepost=1.00m } , new Site { RouteId= '' A '' , StartMilepost=1.00m , EndMilepost=2.00m } , new Site { RouteId= '' A '' , StartMilepost=5.00m , EndMilepost=7.00m } , new Site { RouteId= '' B '' , StartMilepost=3.00m , EndM...
How to use IEnumerable.GroupBy comparing multiple properties between elements ?
C#
Before you rush to think about the ? ? null coalescing operator : The problem here is when whether myParent or objProperty are null , then it will throw an exception before even reaching the evaluation of strProperty.To avoid the following extra null checkings : I generally use something like this : So if the object is...
string result = myParent.objProperty.strProperty ? ? `` default string value if strObjProperty is null '' ; if ( myParent ! = null ) { if ( objProperty ! = null ) { string result = myParent.objProperty.strProperty ? ? `` default string value if strObjProperty is null '' ; } } string result = ( ( myParent ? ? new Parent...
1 linear , beauty and clean way to assign value if null in C # ?
C#
Is there a difference here ? andThe second method does n't seem to work for me but I 've seen it used when Google-ing 'how to remove an event handler ' . Edit : Actually neither are working for me , even so should either work interchangeably ? Update : The reason these did n't appear to work for me is because I had Aut...
Button1.Click -= new EventHandler ( Button1_Click ) ; Button1.Click -= Button1_Click ;
Is there a difference between these 2 ways of removing an event handler ?
C#
My application has InstrumentFactory - the only place where I create Instrument instance . Each instrument instance contains several fields , such as Ticker=MSFT and GateId=1 and also unique Id =1.And now I realized that I almost never need Instrument instance . In 90 % of cases I just need Id . For example now I have ...
public InstrumentInfo GetInstrumentInfo ( Instrument instrument ) { return instrumentInfos [ instrument.Id ] ; } public InstrumentInfo GetInstrumentInfo ( int instrumentId ) { return instrumentInfos [ instrumentId ] ; }
When I need some item , should I just use its `` int id '' instead ?
C#
I was testing the effects of calling a virtual member in a constructor , and discovered that when calling that member the resulting exception was wrapped within a TargetInvocationException.According to the docs this is : The exception that is thrown by methods invoked through reflectionHowever I 'm unaware of any invok...
class ClassA { public ClassA ( ) { SplitTheWords ( ) ; } public virtual void SplitTheWords ( ) { //I 've been overidden } } class ClassB : ClassA { private readonly String _output ; public ClassB ( ) { _output = `` Constructor has occured '' ; } public override void SplitTheWords ( ) { String [ ] something = _output.Sp...
Are virtual members called via reflection ( in normal circumstances ) ?
C#
I 'm am working on having a screen that allows the user to change the order of items , and when the user clicks on the `` Save '' button my javascript will look at the order of < li > items , and in the order it finds them it will form an array with an id value and send it back to my application . I expect the POST dat...
stepIds=5 & stepIds=2 & stepIds=1 public virtual ActionResult Reorder ( short [ ] stepIds ) { }
Can I assume that the order I send values over POST will be model bound to an array in the same order in Asp.net MVC ?
C#
On my server I have a route that generates a pdf for a user . When the generation takes longer than a specified amount of time , the route is supposed to return an accepted status code and send a email to the user when the processing is finished . The issue I am having is that the Task.Delay is not being respected . No...
[ HttpPost ] [ Route ( `` foo '' ) ] public async Task < IHttpActionResult > Foo ( [ FromBody ] FooBody fooBody ) { var routeUser = await ValidateUser ( ) ; async Task < Stream > CeatePdfFile ( ) { var pdf = await createPdfFromFooData ( fooBody ) ; return await pdfFileToStream ( pdf ) ; } var delay = Task.Delay ( PdfGe...
C # Async ApiController route issue resolving Task.WhenAny with a Task.Delay
C#
I have EditorFor in my View.Like this Also I Action in controller that find all NULL in table from database and update it with some value , here is codeIn Index View I tap button that goes to Update Action and launch itHere is codeBut here is update with static value , and I want to recieve value from VIew . How I need...
@ Html.EditorFor ( model = > model.First ( ) .Link , new { htmlAttributes = new { @ class = `` form-control '' , placeholder = `` Email '' , id= `` start '' } } ) public ActionResult Update ( string start= '' lol '' ) { ApplicationDbContext context = new ApplicationDbContext ( ) ; IEnumerable < InvitationMails > custom...
Pass value from EditorFor to method
C#
Is it possible to get the name of another method in the same class but without using a manually written string ? You may ask why : well the reason is that I must invoke the method later on like this Invoke ( `` otherMethod '' ) , however I do n't want to hardcode this string myself as I ca n't refactor it anymore withi...
class MyClass { private void doThis ( ) { // Wanted something like this print ( otherMethod.name.ToString ( ) ) ; } private void otherMethod ( ) { } }
How to get the methodname from a known method ?
C#
I have a problem with my query using dapper , whether someone imagine to help me and say where I 'm doing the wrong , is currently showing me an error at the date when I put a breik point , how to correct it properly ? thank you all for helpthis is my current codeand this is the result with which I get an error
public string GetBezeichnung ( int LP , DateTime date ) { using ( IDbConnection connection = new System.Data.SqlClient.SqlConnection ( ) ) { connection.ConnectionString = _ConnectionString ; var output = connection.Query < string > ( `` SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = `` + LP + `` AND ZER_Datum ...
Selection using dapper
C#
I have a hierarchy of TrendProviders which are used to provide a series of datapoints ( trends ) from different sources.I have started with the generic interface : TrendResult is a result class with the obtained trend data and operation status code : TrendResultCode is as follows : There are also two types ( so far ) o...
public interface ITrendProvider < T > where T : TrendResult { IEnumerable < T > GetTrends ( ) ; } public class TrendResult { public TrendResult ( ) { Points = new Dictionary < DateTimeOffset , decimal > ( ) ; } public TrendResultCode Code { get ; set ; } public string Name { get ; set ; } public string Identifier { get...
c # polymorphism + generics design - advice needed
C#
Imagine I have a list of items : Now from somewhere a server tells my application that element B was removed , yet it only provides the entire new list , not the exact change details.Since WinRT ListViews automatically animate addition , removal , and movement of items inside them , I would prefer not to refresh the ba...
- A - B - C 1 . Delete element B 2 . Add new element D to position 3
Replicating changes in a list
C#
I 'm struggling with multithreading in C # ( which I 'm learning just for fun ) and realise I probably do n't understand what a thread is ! When I run the code below , I was expecting to get something like the following output . ( possibly in a different order ) However , I 'm getting something likeI had assumed that e...
T1 : 11T2 : 11T3 : 11T4 : 11T5 : 11T6 : 11 T1 : 11T2 : 11T3 : 12T5 : 12T6 : 13T4 : 11 using System ; using System.Threading ; using System.Threading.Tasks ; namespace TestThreads { class TestThreadLocal { static void Main ( ) { ThreadLocal < int > local = new ThreadLocal < int > ( ( ) = > { return 10 ; } ) ; Task t1 = ...
ThreadLocal < T > - What is a thread ? ( C # )
C#
I have ef classes like this : And want to make request like : Problem : Problem is that when I fetch for example 1000 products this partmake query for every row and its very slow.What I seen in debugger that for each product make query to fetch BannedIn , but should be already fetched cause I have IncludeWhat need to b...
class Product { public int ProductId { set ; get ; } ... public List < ProductBannedIn > BannedIn ; } public class ProductBannedIn { public int ProductId { set ; get ; } public Product Product { set ; get ; } public int CountryId { set ; get ; } public Country Country { set ; get ; } } ... //query - added some filters ...
Linq request make a lot of queries to DB
C#
Considering the next struct ... and the next matrix definitionswhich one of the matrices will use less memory space ? or are they equivalent ( byte per byte ) ?
struct Cell { int Value ; } var MatrixOfInts = new int [ 1000,1000 ] ; var MatrixOfCells = new Cell [ 1000,1000 ] ;
Is equivalent the memory used by an array of ints vs an array of structs having just one int ?
C#
As input to another program I am using I need to input a delegate of the form : I want the function to be sent in to be F ( a , b ) =a+b*c+dwhere c and d are known constants known at runtime.So what I need is some method which takes the values c and d , and then gives me a function F ( a , b ) . What I think I need to ...
Func < double , double , double > . double der ( double a , double b , double c , double d ) { return a + b * c + d ; }
Create a function which gives us another function
C#
I am using an int array to hold a long list of integers . For each element of this array I want to check if it is 1 , if so do stuff relevant to 1 only , else if it is a 2 , do other stuff relevant to 2 , and so forth for each value stored in the array . I came up with the code below but it is n't working as expected ,...
int [ ] variable1 = MyClass1.ArrayWorkings ( ) ; foreach ( int i in variable1 ) { if ( variable1 [ i ] == 1 ) { // arbitrary stuff } else if ( variable1 [ i ] ==2 ) { //arbitrary stuff } }
Cycling through contents of array issue
C#
Why are exceptions always accepted as a return type ( thrown ) ? Valid example 1 : Invalid example ( obviously ) : Valid example 2 : I can see that my `` Invalid Example '' is 'throwing ' and not 'returning ' the Exception , however , my method does never return the type defined by the method . How come my compiler all...
public string foo ( ) { return `` Hello World ! `` ; } public string foo ( ) { return 8080 ; } public string foo ( ) { throw new NotImplementedException ( `` Hello Stackoveflow ! `` ) ; }
Why are exceptions always accepted as a return type ( when thrown ) ?
C#
I 'm attempting to return an image from a server route , but I 'm getting one that is 0 bytes . I suspect it has something to do with how I 'm using the MemoryStream . Here 's my code : Through debugging I have verified that the PdfToImages method is working and that imageMemoryStream gets filled with data from the lin...
[ HttpGet ] [ Route ( `` edit '' ) ] public async Task < HttpResponseMessage > Edit ( int pdfFileId ) { var pdf = await PdfFileModel.PdfDbOps.QueryAsync ( ( p = > p.Id == pdfFileId ) ) ; IEnumerable < Image > pdfPagesAsImages = PdfOperations.PdfToImages ( pdf.Data , 500 ) ; MemoryStream imageMemoryStream = new MemorySt...
Not Receiving Data from Route C #
C#
I need to generate all the substring of a given length , of a string.For example all the substrings of length 3 of `` abcdefg '' are : For this task I wrote this function : that I use like this : I wonder if it is possible to write the same function avoiding the variable result and using yield
abcbcdcdedefefg public static IEnumerable < string > AllSubstringsLength ( string input , int length ) { List < string > result = new List < string > ( ) ; for ( int i = 0 ; i < = input.Length - length ; i++ ) { result.Add ( input.Substring ( i , length ) ) ; } return result ; } foreach ( string s in AllSubstringsLengt...
Generating all the substring of a given length using yield
C#
We knows that TPL ( so PLINQ too ) does n't consume all cores if he think that task is easy and executes it on single core . But he does it even for a complicated task ! For example , here is code from article about Java parallelism : and results : you can see that multithreaded version executed ~19 times faster than s...
import org.openjdk.jmh.infra.Blackhole ; import org.openjdk.jmh.annotations . * ; import java.util.concurrent.TimeUnit ; import java.util.stream.IntStream ; import java.math.BigInteger ; @ Warmup ( iterations=5 ) @ Measurement ( iterations=10 ) @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.MICROSECON...
What heuristic uses TPL to determine when to use multiple cores
C#
My C # application server.exe is critical to my business operations and ideally needs to run without interruption 24/7 . The code is rock solid but one thing that 's out of my control is the poor quality of inbound data feeds that are generated by third parties . I 'll occasionally receive data feeds that contain anoma...
public interface IFeedProcessor { bool ProcessFeed ( String filePath ) ; //returns false on failure , true on success } internal class FeedProcessor1 : IFeedProcessor { public FeedProcessor1 ( ) { } bool ProcessFeed ( String filePath ) { /*implementation*/return true ; } } internal class FeedProcessor2 : IFeedProcessor...
How can I get a portion of my C # app to load dynamically without app restart ?
C#
In my C # code , I need to evaluate two non-null variables . I worked out a set of if-else if statements , but in my mind it looks ugly and a little bit too sloppy , even if it is correct.I looked in the MSDN Library and saw only examples for selection based on a single variable.Is there a cleaner and more compact way ...
public ActionResult Index ( string searchBy , string orderBy , string orderDir ) { var query = fca.GetResultsByFilter ( searchBy ) ; if ( orderBy == `` Campus '' & & orderDir == `` Asc '' ) { query = query = query.OrderBy ( s = > s.Campus ) .ThenBy ( s = > s.Student_Name ) ; } else if ( orderBy == `` Campus '' & & orde...
Is there an efficient way to do a selection statement with two variables ?
C#
I have some context in code to be switched depending on whether it is running under test or release.Say in my product coding : The way I am thinking about is make a TestFlag class : This seems verbose if I have many place to do that . Is there any good pattern to do it ?
PublishRequest ( ) ; // the real one//PublishRequestPsudo ( ) ; // the one want to be run during unit test if ( ! TestFlag.PublishFlag ) { PublishRequest ( ) ; } else { PublishRequestPsudo ( ) ; }
Is there any good way to switch different context between Unit Test and Release . in C #