lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a variable called full_name if the full_name has a string length > 5 I would like to set nm to the first 4 characters of full_name otherwise I would like to set nm to all the characters of full_name . I 'm totally confused with the `` ? '' operator . Could I use it for this ?
var nm ; if ( full_name.Length > 5 ) { nm = full_name.Substring ( 0 , 4 ) ; } else { nm = full_name ; } ;
Confused with the ? operator in C #
C#
Below is an implementation of an interlocked method based on Interlocked.CompareExchange.Is it advisable for this code to use a SpinWait spin before reiterating ? I have seen SpinWait used in this scenario , but my theory is that it should be unnecessary . After all , the loop only contains a handful of instructions , ...
public static bool AddIfLessThan ( ref int location , int value , int comparison ) { int currentValue ; do { currentValue = location ; // Read the current value if ( currentValue > = comparison ) return false ; // If `` less than comparison '' is NOT satisfied , return false } // Set to currentValue+value , iff still o...
Should interlocked implementations based on CompareExchange use SpinWait ?
C#
I have 3 classes witch inherit another class called ParentClass and each of the 3 has the following code insideIn my main form i have a variable like this ParentClass PClass = new OneOfTheThreeClassesHow can i call the DrawBAckground method of those classes using that variable , from my form 's paint event ?
public void DrawBackground ( Graphics e , Rectangle rect ) { e.FillRectangle ( Brushes.Red , rect ) ; }
Call method and draw
C#
I 'm trying to `` toggle '' between my CORS policies depending on the environment the application is running.I have two policies declared as follows : These policies should be only applicable to a few controllers so I 'm using the attribute to apply them : PublicAPI policy should be valid for production where domains a...
services.AddCors ( options = > { options.AddPolicy ( CORSPolicies.PublicApi , builder = > builder .AllowAnyHeader ( ) .WithMethods ( `` POST '' , `` GET '' ) .WithOrigins ( `` https : //domain1.com '' , `` https : //domain2.com '' ) ) ; options.AddPolicy ( CORSPolicies.Dev , builder = > builder .AllowAnyHeader ( ) .All...
Handling CORS policy for multiple environment in ASP.NET Core 3.1
C#
I have a function that adds a double to another double but I need to add only to the digits after the decimal point and the number of digits varies based on the size of the number.I 'm wondering if there is n't a simpler way to do this without having to convert the number to string first and then adding to the decimal ...
public double Calculate ( double x , double add ) { string xstr ; if ( x > = 10 ) xstr = x.ToString ( `` 00.0000 '' , NumberFormatInfo.InvariantInfo ) ; if ( x > = 100 ) xstr = x.ToString ( `` 000.000 '' , NumberFormatInfo.InvariantInfo ) ; if ( x < 10 ) xstr = x.ToString ( `` 0.00000 '' , NumberFormatInfo.InvariantInf...
Get decimals of a double ?
C#
I have this code : When I debug in Visual Studios and hover my mouse over the num array it shows the length is 1000 and then the first 14 characters are 0 and everything after that is a `` ? `` .Assigning numbers [ 15 ] + does n't change anything nor does it crash the program .
int [ ] numbers = new int [ 1000 ] ;
Arrays wo n't go past 14
C#
Is there anything special I should be doing to gracefully shut down a thread when it has performed a WCF call during its processing ? I seem to be getting a memory leak on my server and I have tracked it down to making a WCF call from my worker threads . I create the threads in a simple way , like this ... ... and the ...
var schedule = new Schedule ( ) ; var scheduleThread = new Thread ( New ParameterizedThreadStart ( schedule.Run ) ) ; scheduleThread.SetApartmentState ( ApartmentState.STA ) ; scheduleThread.Priority = ThreadPriority.Lowest ; scheduleThread.Start ( null ) ; public void Run ( object param ) { var wcf = new TestServer.Te...
Extra steps when shutting down thread that used WCF ?
C#
I have a model like the following one : How would I have to make the corresponding view form , to get the Model correctly binded after the post request ? The user should be able to select the various Fields with checkboxes and the Model should contain the selected ones.In the Action method below , the Model 's members ...
public class TestModel { public IList < Field > Fields { get ; set ; } } public class Field { public String Key { get ; set ; } public String Value { get ; set ; } } public ActionResult XY ( TestModel model ) { [ ... ] }
Bind value to complex Type
C#
I have an ASP.NET MVC project , and am writing my service something along the lines of this : And my DbContext class : This runs fine for the most part , but the problem arises when I want to try and test it . I 'm following the general guidelines here with mocking it out , but that 's only if the DbContext is declared...
public class UserService : IUserService { public void AddUser ( UserModel userModel ) { if ( ModelState.IsValid ) { var user = new User { FirstName = userModel.FirstName , LastName = userModel.LastName , Email = userModel.Email , Age = userModel.Age } ; using ( var context = new MyDbContext ( ) ) { context.Users.Add ( ...
ASP.NET Testing DbContext in local methods
C#
When I use the following code : The mono compiler crashes . Is this due to a semantical error ( something that is not allowed in the language ) , but is unnoticed by the compiler or is this a compiler-bug ? Version : Mono 2.10.8.1I 've filed a bug report at bugzilla ( https : //bugzilla.xamarin.com/show_bug.cgi ? id=15...
using System ; namespace Foo { [ Flags ] public enum Bar : ulong { None = 0x0000000000000000 , A = 0x8000000000000000 , B = 0x0000000000000001L | A , C = 0x0000000000000002L | B , D = 0x0000000000000004L | A , All = A | B | C | D } }
Why is field referencing not allowed in an enum ( or is this a compiler bug ? )
C#
I found an unusual sample in FCL code.This is method in System.IO.BinaryReader : What impact on the execution logic has 'copyOfStream ' ?
protected virtual void Dispose ( bool disposing ) { if ( disposing ) { Stream copyOfStream = m_stream ; m_stream = null ; if ( copyOfStream ! = null & & ! m_leaveOpen ) copyOfStream.Close ( ) ; } m_stream = null ; m_buffer = null ; m_decoder = null ; m_charBytes = null ; m_singleChar = null ; m_charBuffer = null ; }
BinaryReader.Dispose ( bool disposing ) creates a local reference to stream . Why ?
C#
What I am asking is partly related to design pattern.Lets say I have an IDrawing interface.Two other basic classes named TextDrawing and ShapeDrawing implement this , and I have a View class that knows how to draw these ! But I have more complex drawing classes that also implement IDrawing interface but are composed of...
public interface IDrawing { } public class TextDrawing : IDrawing { } public class ShapeDrawing : IDrawing { } public class SignDrawing : IDrawing { public TextDrawing Text { get ; set ; } public ShapeDrawing Border { get ; set ; } } public class MoreComplexDrawing : IDrawing { public TextDrawing Text { get ; set ; } p...
How to handle composed classes in C #
C#
I would expect the result of percentOfSum to be the original value of value ( 5000 ) I need a way to do calculations like this back and forth , and I can simply not do ANY rounding.Any help ?
decimal hundred = 100 ; decimal value = 5000 ; decimal sum = 1100000 ; decimal valuePercentOfSum = value / sum * hundred ; //result = 0.4545454545454545454545454500Mdecimal percentOfSum = sum / hundred * valuePercentOfSum ; //result = 4999.9999999999999999999999500M
C # percent calculation with decimal type causes problems
C#
How is it possible ? Does n't it violate encapsulation principle ?
namespace test { class Attr : Attribute { public Attr ( int e ) { } } [ Attr ( E ) ] class Test { private const int E = 0 ; } }
Why it is possible to access private const field from attribute ?
C#
According to c # 7.2 The `` in '' operator Passes a variable in to a method by reference . Can not be set inside the method.and we can write method like thisand call it usingNow my question is that , what is the Big difference between calling that one and this one** ( with or without `` in '' operator ) **and Call like...
public static int Add ( in int number1 , in int number2 ) { return number1 + number2 ; } Add ( ref myNo,4 ) ; public static int Add ( int number1 , in int number2 ) { return number1 + number2 ; } Add ( 3,4 ) ;
Difference Between `` in '' Operator and Simple Value Pass c #
C#
My categories.xml file is given belowand My attibutes.xml file is given belowI bound my attributeDropdown on selection of categoriesDropDown . Code is given belowNow the problem is two attributes named AC and Alarm are in two categories Real Estate and Property For Rent . How can I bind these attributes on selection of...
< categories > < root name= '' Cars -Vehicles '' id= '' CV '' > < /root > < root name= '' Personals '' id= '' PER '' > < /root > < root name= '' Real Estate '' id= '' RE '' > < /root > < root name= '' Property For Rent '' id= '' PFR '' > < /root > < root name= '' Community '' id= '' COM '' > < /root > < /categories > <...
Confuse What should be my Xpath Expression ?
C#
I have code where being able to perform this type of implicit cast would save me writing a lot of boilerplate interface implementation code.This seems to be the sort of thing which covariance was supposed to help with.But I always get this error on the return a ; line above : error CS0266 : Can not implicitly convert t...
static IEnumerable < U > DoSomething < T , U > ( IEnumerable < T > a ) where T : U { // Works , compiler can compile-time statically cast // T as U. T testA = default ( T ) ; U testB = testA ; // And the following works , though : IEnumerable < string > test2A = null ; IEnumerable < object > test2B = test2A ; // Doesn ...
Why do covariant implicit casts ignore generic constraints ?
C#
If I register some callbacks to a CancellationToken before it is cancelled , it seems they will be invoked in reverse order when the token is cancelled . Is this invocation order guaranteed ? This will output
var cts = new CancellationTokenSource ( ) ; var token = cts.Token ; token.Register ( ( ) = > Console.WriteLine ( `` 1 '' ) ) ; token.Register ( ( ) = > Console.WriteLine ( `` 2 '' ) ) ; token.Register ( ( ) = > Console.WriteLine ( `` 3 '' ) ) ; cts.Cancel ( ) ; 321
Registered CancellationToken callback invocation order
C#
Today I learned about value types and reference types.I am having one doubt in the code sample below : Here the string builder value and class member variable value is updated , but why is FuntionString ( str ) ; not updating the str value ? ( Why is it not passed as a reference ? )
class Program { static void Main ( string [ ] args ) { StringBuilder sb = new StringBuilder ( ) ; FunctionSB ( sb ) ; Console.WriteLine ( sb ) ; //sb updated customer c = new customer ( ) ; FunctionClass ( c ) ; Console.WriteLine ( c.s ) ; //updated class value String str = `` '' ; FuntionString ( str ) ; Console.Write...
Strings not behaving as a reference type
C#
Consider this code : Each time I run it , I get StackOverflowException on a different value of i variable . For example 16023 , 16200 , 16071 . What 's the reason behind this ? Is it a bug in C # compiler ?
private static int i = 0 ; static void Main ( string [ ] args ) { DoSomething ( ) ; Console.ReadLine ( ) ; } public static void DoSomething ( ) { Console.WriteLine ( i ) ; ++i ; DoSomething ( ) ; }
Why stack overflow exception is thrown on different call numbers ?
C#
This will be so easy for some of you programming geniuses out there but I am a student who recently began learning about C # ( and programming in general ) and I find myself ... . stuck . This is an assessment I am working on so I am not looking for a copy/paste answer , it would be preferable if I could find out where...
using System ; namespace Assessment { class MainClass { public static void Main ( string [ ] args ) { //Decalre Variables Random r = new Random ( ) ; int PlayerNumber1 = r.Next ( 6 , 25 ) ; int PlayerNumber2 = r.Next ( 6 , 25 ) ; int DealerNumber1 = r.Next ( 6 , 25 ) ; int DealerNumber2 = r.Next ( 6 , 25 ) ; int Player...
Creating a c # function to compare int results
C#
I 'm trying to figure out why my console app is not torn down by an unhandled task exception . All I do is create a task where I immediately throw an exception . Finally I force GC . In the first example I have a handler for the TaskScheduler.UnobservedTaskException event and I can see the exception get handled.Output ...
static async Task ThrowsException ( ) { Console.WriteLine ( `` Throwing ! `` ) ; throw new Exception ( `` Test exception '' ) ; } static void Main ( string [ ] args ) { TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException ; ThrowsException ( ) ; Console.WriteLine ( `` Collecting garbage . `` )...
Console application not torn down by an unhandled task exception
C#
While I was looking through the C # Language Specification v4.0 I noticed that there is a group of rules defined as this : When I tried to match this statement ( which is correct statement by the way , I 've seen it used in a project ) to the given rules I did n't see a way how this can be done . Should n't be base-acc...
invocationExpression : primaryExpression ' ( ' argumentList ? ' ) 'primary-expression : primary-no-array-creation-expression array-creation-expressionprimary-no-array-creation-expression : literal simple-name parenthesized-expression member-access invocation-expression element-access this-access base-access post-increm...
Is the base access defined correctly in the C # Language Specification 4.0 ?
C#
I have a datamodel used by multiple application that I now needs to be used by other developers outside the team . The model should only be made partialy available to the developers.I wonder how I best approach this : my current approach is to create a new project that just copies the orginal model and only include the...
namespace Model { public class Car { private double m_speed ; private FuelType m_fuelType ; public double Speed { get { return m_speed ; } set { m_speed = value ; } } public FuelType FuelType { get { return m_fuelType ; } set { m_fuelType = value ; } } } } using Model ; namespace ModelLite { public class Car { private ...
defining interface
C#
I have this issue in which I have a strnig with among other things the literal expression `` \\ '' on several occasions and I want to replace it with `` \ '' , when I try to replace it with string.replace , only replcaes the first occurrence , and if I do it with regular expression it does n't replace it at allI checke...
example = `` \\\\url.com\\place\\anotherplace\\extraplace\\ '' ; example = example.replace ( `` \\\\ '' , '' \\ '' ) ; returns example == `` \\url.com\\place\\anotherplace\\extraplace\\ '' ; example = Regex.Replace ( example , '' \\\\ '' , '' \\ '' ) ; returns example = `` \\\\url.com\\place\\anotherplace\\extraplace\\...
Odd behaviour replacing `` \ ''
C#
I have this pattern : And the replacement pattern is this : The problem is that this word : setesinwill be transformed to : setestakinstead of setetakFor some reason , in always takes precedence to sin in the pattern.How can I enforce the pattern to follow that order ?
( \w+ ) ( sin|in|pak|red ) $ $ 1tak
Regex capture order : wrong alternative matched after greedy pattern
C#
Is it possible to return only those who match all the list values in LINQ ? I have one table klist in which two columns are available : and I have a list that contains tid value : now the tid list have 1 and 2 value.So my question is that from klist table I will only get those kid which contain all the tid list values ...
Kid - Tableid 001 1001 2002 1003 3004 1004 2 List < int > tid = new List < int > ( ) ; tid.Add ( 1 ) ; tid.Add ( 2 ) ; kid - 001kid - 004 var lb = Klist.Where ( t = > tid .Contains ( t.Tableid ) ) .Select ( k = > k.Kid ) .Distinct ( ) .ToList ( ) ; kid - 001kid - 002kid - 003kid - 004
Is this possible in LINQ ?
C#
I need to display the Single user schedule for every week like Timetable , Scenario : A faculty is assigned to Multiple batches in a single week ( E.g : BBA , Maths and Forenoon for Hour 1 and 2 ) & ( MBA , Maths , Forenoon for Hour 3 & 4 ) in a same date say ( 30-06-2015 ) .I row of gridview will store as 1 and 2 row ...
CREATE TABLE [ dbo ] . [ test ] ( [ datedif ] NVARCHAR ( 50 ) NOT NULL , [ hour ] INT NULL , [ subject ] NVARCHAR ( MAX ) NULL , [ faculty ] NVARCHAR ( MAX ) NULL , [ attendence ] BIT NULL , [ dayweek ] NVARCHAR ( 50 ) NULL , [ weekmonth ] NVARCHAR ( MAX ) NULL , [ batch ] NVARCHAR ( MAX ) NULL , [ section ] NVARCHAR (...
Multiple column values in where clause
C#
What is the rational ( if any ) behind the following behavior : Why are the comparison operators behaving differently from the default comparer for nullables ? More weirdness :
int ? a = null ; Console.WriteLine ( 1 > a ) ; // prints FalseConsole.WriteLine ( 1 < = a ) ; // prints FalseConsole.WriteLine ( Comparer < int ? > .Default.Compare ( 1 , a ) ) ; // prints 1 var myList = new List < int ? > { 1 , 2 , 3 , default ( int ? ) , -1 } ; Console.WriteLine ( myList.Min ( ) ) ; // prints -1 ( co...
Weird nullable comparison behavior
C#
I 'll let the code do the talking : If ThingServiceInstance is an IThingServiceInstance and MyThing is an IThing , why ca n't I add a ThingServiceInstance < MyThing > to a collection of IThingServiceInstance < IThing > ? What can I do to make this code compile ?
using System.Collections.Generic ; namespace test { public interface IThing { } // ca n't change this - it 's a 3rd party thing public interface IThingRepository < T > where T : class , IThing { } // ca n't change this - it 's a 3rd party thing public interface IThingServiceInstance < T > where T : class , IThing { ITh...
Ca n't add a concrete instance of a generic interface to a generic collection
C#
Compiler ( Visual Studio 2010 , C # 4.0 ) says `` Not all code paths return a value '' . Why ?
public static int Test ( int n ) { if ( n < 0 ) return 1 ; if ( n == 0 ) return 2 ; if ( n > 0 ) return 3 ; }
In what a case wo n't this function return a value ? Why does the compiler report an error ?
C#
Suppose you have a class that is frequently ( or even exclusively ) used as part of a linked list . Is it an anti-pattern to place the linkage information within the object ? For example : An often-cited recommendation is to simply use a generic container class ( such as java.util.LinkedList in Java ) , but this create...
public class Item { private Item prev ; private Item next ; ... }
Is linkage within an object considered an anti-pattern ?
C#
I recently joined a company where they use TDD , but it 's still not clear for me , for example , we have a test : What 's the purpose of it ? As far as I understand , this is testing nothing ! I say that because it 's mocking an interface , and saying , return true for IsRunning , it will never return a different valu...
[ TestMethod ] public void ShouldReturnGameIsRunning ( ) { var game = new Mock < IGame > ( ) ; game.Setup ( g = > g.IsRunning ) .Returns ( true ) ; Assert.IsTrue ( game.Object.IsRunning ) ; }
Why this particular test could be useful ?
C#
I have a unit test which is intended to check the access right and also make sure there is enough access right to file system before constructing a class . But , I think my unit test is violating the unit testing principle ( FIRST ) such as : Isolated/Independent and Thorough which are talking about building an indepen...
[ Test ] public void DirectoryNotWritableTest ( ) { var tempPath = Path.Combine ( Path.GetTempPath ( ) , `` EventFileDirectoryWriteDeniedTest '' ) ; int pageSize = 10 ; try { if ( Directory.Exists ( tempPath ) ) Directory.Delete ( tempPath , true ) ; var directoryInfo = Directory.CreateDirectory ( tempPath ) ; var secu...
Is this Unit Test implemented correctly ?
C#
Following a Pluralsight course I 'm coding an ASP.NET 5/MVC 6 web app from effectively scratch . When referencing an object in the format such as : orin an .cshtml file , Intellisense is showing an error , saying the files ca n't be found suggesting the paths should be instead : However using the first group of paths r...
~/js/site.js ~/css/site.css ~/wwwroot/js/site.js~/wwwroot/css/site.css { `` version '' : `` 1.0.0-* '' , `` compilationOptions '' : { `` emitEntryPoint '' : true } , `` dependencies '' : { `` Microsoft.AspNet.IISPlatformHandler '' : `` 1.0.0-rc1-final '' , `` Microsoft.AspNet.Mvc '' : `` 6.0.0-rc1-final '' , `` Microso...
ASP.Net intellisense incorrectly suggesting webroot for paths
C#
Consider the code : The problem is that if we mark DoWork ( ) in BaseClass as virtual so that it can be overridden by child classes , it prevents it from calling into IChildInterface 's default implementation of DoWork ( ) , causing StackOverflowException.If we remove virtual modifier from DoWork ( ) in the BaseClass ,...
class ChildClass : BaseClass { public void Method1 ( ) { } //some other method } abstract class BaseClass : IChildInterface { public virtual // < - If we add virtual so that this method can be overridden by ChildClass , we get StackOverflowException and DoWork ( ) implementation in IChildInterface is never called . voi...
Making member virtual prevents calling default interface implementation and causes StackOverflowException in C # 8
C#
In an MVVM design , suppsoe if the View creates the ViewModel , how should the ViewModel know about its Model ? I read from a few places that the Model can be passed into ViewModel through its constructor . So it looks something like : Since the View is creating the ViewModel , and to pass the Model into the ViewModel ...
class ViewModel { private Model _model ; public ViewModel ( Model model ) { _model = model ; } }
How should a Model get passed into the ViewModel ?
C#
Consider the following code that is not CLS Compliant ( differs only in case ) : So i changed it to : Which is also not CLS-compliant ( has leading underscore ) .Is there any common naming scheme for members/properties that does n't violate cls compliance
protected String username ; public String Username { get { return username ; } set { username = value ; } } protected String _username ; public String Username { get { return _username ; } set { _username = value ; } }
What C # naming scheme can be used for Property & Member that is CLS compliant ?
C#
I 've came across an interesting issue for which I 've found no explanation yet ... Given the very simple MVVM WPF application below , why is the list bound to the combo box only if its visibility in the ViewModel is set to public ? Changing the TestList visibility to internal raises no error or warning at compile time...
class TestModel { internal List < string > Musketeers { get ; private set ; } public TestModel ( ) { Musketeers = new List < string > { `` Athos '' , `` Porthos '' , `` Aramis '' } ; } } < Window x : Class= '' TestWpfApplication.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmln...
What should be the ViewModel members visibility ?
C#
C # windows form : - > Database : AccessI have made a query somewhat like thisthe above query is for getting records that have Alok and 6 charachter in their name.If I execute this query in access it works fine and fetches the record but when I try it in c # OrBoth of them does not work and i have also tried both type ...
Select * from Emp where E_Name Like 'Alok* ? ? ? ? ? ? ' Select * from Emp where E_Name Like 'Alok* ? ? ? ? ? ? ' Select * from Emp where E_Name Like 'Alok % ? ? ? ? ? ? ' Microsoft.ACE.OLEDB.12.0 ; Microsoft.Jet.OLEDB.4.0 ;
Like condition is not working properly
C#
I calculate the angles of a triangle , and I do n't understand why I get a negative angle for some acute angle . For example : it return sin = -0.965 and angle = -44.When scientific calculator show sin = 0.0775My triangle has such lengths 6.22 , 6.07 and 1.4 then there is n't option to had negative angle .
var sin = Math.Sin ( 4.45 ) ; var radians = Math.Atan ( sin ) ; var angle = radians * ( 180 / Math.PI ) ;
The angle sin returns a negative result for the acute angle
C#
I have these two functionsI want to use the second overload when I do the following callIs there a way I can force it to go to the second definition of the method ? The compilation error I have is : This call is ambiguous between the following methods or properties : ( and then the two methods above ) PS : I have n't c...
public static string Function1 ( string id , params string [ ] ) { return Function1 ( id , null , null , params ) } public static string Function1 ( string id , string id2 , Object a , params string [ ] ) { string id = id , if ( IsValidId ( id ) ) { start = new ProcessStartInfo ( ) ; start.Arguments = params ; if ( str...
Overloaded function with params string [ ] in the signature
C#
I got yelled at for trying to use the word question in the title so this is what I came up with . At any rate , this is a purely academic question about parameter types . OK , so here is what I get . That is clear and unambiguous to me ( Astute readers will recognize this as a simple extension of an example found on pa...
using System ; namespace TypeParamTest { internal class Program { private static void Main ( string [ ] args ) { PrintType ( 1 , new object ( ) ) ; Console.ReadKey ( ) ; } static void PrintType < T , Ttwo > ( T first , Ttwo second ) { Console.WriteLine ( typeof ( T ) + `` : `` + typeof ( Ttwo ) ) ; } } } List < TOutput...
A parameter type ruined my Func < shui >
C#
I 've spent some time on the internet trying to find a solution , but my skills in C # are at a beginner level and I did not find any ways to do what i wanted to.So here is the situation : I have a web service that return an object to me , in this object there is a two dimensional table . What I 'd like to do is runnin...
// creation of a list like : List < String , List < String > > myListfor ( int i = 0 ; i < outPut.errors.Length ; i++ ) { string error = outPut.errors [ i ] .data.label ; //myList.add ( error ) ; if ( outPut.errors [ i ] .data.label ! = `` '' & & outPut.errors [ i ] ! = null ) { for ( int j = 0 ; j < outPut.errors [ i ...
C # list < string , list < string > > how to ?
C#
Never sure where to place functions like : I create a Toolbox class for each application that serves as a repository for functions that do n't neatly fit into another class . I 've read that such classes are bad programming practice , specifically bad Object Oriented Design . However , said references seem more the opi...
String PrettyPhone ( String phoneNumber ) // return formatted ( 999 ) 999-9999String EscapeInput ( String inputString ) // gets rid of SQL-escapes like '
Creating a Catch-All AppToolbox Class - Is this a Bad Practice ?
C#
I was trying to do a join and then a group by , My grouped information that is returned is great ! works like a charm , but i still need access to values outside the grouping , if that makes sense.. I found an example on stackoverflow , which probably explains it betterNow this seems to work great , problem is in my si...
var query = from c in context.Contacts join o in context.Orders on c.Id equals o.CustomerId select new { Contact = c , Order = o } into ContactAndOrder group ContactAndOrder by ContactAndOrder.Order.Id into g select new { g.Key , ContactWhatever = g.Sum ( co = > co.Contact.Whatever ) , OrderWhatever = g.Sum ( co = > co...
Group by multiple tables and still have access to the original query ?
C#
I have WCF service using basicHttpBinding.When client and server are on same network they initial call hangs for about 30 secs than it goes smooth.When I do the same call from client over internet with DNS than it works nicely with no hanging.Client and server are both console applications . Server is running windows 7...
09:33:05,252 [ 1 ] DEBUG ChannelFactoryManager : Created ClientChannel http : //192.168.1.11:18762/DiagnosticService09:33:05,263 [ 1 ] INFO Program : WcfAppender.InitializeWcfAppender : 08:33:0509:33:05,274 [ 1 ] INFO Program : File.Copy ( C : temptest.txt , O : test.txt , true ) : 08:33:0509:33:05,298 [ 1 ] INFO Progr...
WCF initialization on local network hangs for 20 secs
C#
Consider this code : Will the above throw NullReferenceException ? The answer is : it depends on what f ( ) is . If it 's a member method , then yes , it will throw exception . If it 's an extension method , then no , it will not throw any extension.This difference leads to a question : how each type of method is imple...
A a = null ; a.f ( ) ; //Will it throw NullReferenceException ?
Extension Method and Member Method : why each is implemented differently by compilers ( internally ) ?
C#
I have a LINQ query that works in an EF 6 ( Code First ) project . Now I have migrated the code to EF 7 , and this query now throws an exception : ArgumentException : Property 'Int32 ID ' is not defined for type ' X.Models.Domain.MadeChoice'The query : The MadeChoice class : The Room class : The Residence class : Origi...
var madeChoices = from res in X.Instance.Residence join room in X.Instance.Room on res.ID equals room.Residence.ID join madeChoice in X.Instance.MadeChoice on room.ID equals madeChoice.Room.ID where res.ID == residence.ID select room.MadeChoices ; public class MadeChoice { public virtual int ID { get ; set ; } [ Requir...
LINQ query with two joins that worked in EF 6 gives error in EF 7
C#
Consider the following program : The compiler errors on line 9 where TeeAsync is invoked on stringTask because The call is ambiguous between the following methods or properties : 'FunctionalExtensions.TeeAsync < T > ( T , Func < T , Task > ) ' and 'FunctionalExtensions.TeeAsync < T > ( Task < T > , Func < T , Task > ) ...
using System ; using System.Threading.Tasks ; public class Program { public static void Main ( ) { var stringTask = Task.FromResult ( `` sample '' ) ; stringTask.TeeAsync ( st = > Task.CompletedTask ) .Wait ( ) ; } } public static class FunctionalExtensions { public static async Task < T > TeeAsync < T > ( this T sourc...
Ambiguous method overloads when using generic type parameters
C#
I need to distinguish variable names and non variable names in some expressions I am trying to parse . Variable names start with a colon , can have ( but not begin with ) numbers , and have underscores . So valid variable names are : Then I have to pick out other words in the expression that do n't begin with colons . ...
: x : _x : x2 : alpha_x // etc : result = median ( : x , :y , :z ) : [ a-zA-Z_ ] { 1 } [ a-zA-Z0-9_ ] * ( ? < ! : ) ( [ a-zA-Z_ ] { 1 } [ a-zA-Z0-9_ ] * )
Regex ( C # ) - how to match variable names that start with a colon
C#
Eclipse ( at least when using Java ) has the feature to auto highlight all lines in a method where method returns when I place cursor on return type in method definition.Is there also such a feature for C # in Visual Studio + ReSharper 5.1.3 ? Code exampleWhen I place cursor on word string in first line of this example...
string Do ( ) { if ( /**/ ) return `` '' ; // here if ( /**/ ) return `` 1 '' ; // here if ( /**/ ) return `` 2 '' ; // here throw new Exception ( `` '' ) ; // here }
Auto highlight return lines
C#
https : //github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Helpers/Crypto.cs # L159
// Compares two byte arrays for equality . The method is specifically written so that the loop is not optimized . [ MethodImpl ( MethodImplOptions.NoOptimization ) ] private static bool ByteArraysEqual ( byte [ ] a , byte [ ] b ) { if ( ReferenceEquals ( a , b ) ) { return true ; } if ( a == null || b == null || a.Leng...
Why is this loop intentionally not optimized ?
C#
To reduce maintenance in a library I am developing , I am trying to delegate similar functionality to single functions . As an example , say one has a two component vector with Add functions accepting by-ref args and others accepting by-value args . The idea is to simply call the by-ref function within the by-value fun...
struct Vector2 { public float X ; public float Y ; public Vector2 ( float x , float y ) { this.X = x ; this.Y = y ; } public static void Add ( ref Vector2 a , ref Vector2 b , out Vector2 result ) { result.X = a.X + b.X ; result.Y = a.Y + b.Y ; } public static Vector2 Add1 ( Vector2 a , Vector2 b ) { Add ( ref a , ref b...
Delegating value arguments to functions that accept ref arguments
C#
I have some classes and interface : Also , I have some methods and generic methods : And here is a use case : As you can see in GiveFood metod I 'm using MEF . In use case when I cast cat to IAnimal , in GiveFood method typeof ( T ) will be IAnimal not Cat . First question is : Instance of cat variable is Cat class . W...
interface IAnimal { } interface ILiveInZoo { } class Cat : IAnimal , ILiveInZoo { } class Context { private static CompositionContainer Container = null ; public ILiveInZoo GetWhoLivesInZoo ( string name ) { if ( name == `` Cat '' ) return new Cat ( ) ; return null ; } public void GiveFood < T > ( T animal ) where T : ...
Casting classes in generic methods in MEF
C#
I have a sorted ( ascending ) array of real values , call it a ( duplicates possible ) . I wish to find , given a range of values [ x , y ] , all indices of values ( i ) for which an index j exists such that : j > i and x < = a [ j ] -a [ i ] < = yOr simply put , find values in which exists a “ forward difference ” wit...
a= 0 , 1 , 46 , 100 , 185 , 216 , 285 [ true , true , false , false , true , false , false ] int bin_search_closesmaller ( int arr [ ] , int key , int low , int high ) { if ( low > high ) return high ; int mid = ( high - low ) /2 ; if ( arr [ mid ] > key ) return bin_search_closesmaller ( arr , key , low , mid - 1 ) ; ...
Find all differences in sorted array
C#
Can anyone tell me why the following statement evaluates to false ? It does the same thing in Javascript and C++ .
bool myBoolean = .6 + .3 + .1 == .1 + .3 + .6 ; // false
C # strange behavior with + operator
C#
If you have : does this mean that the user wants to call a method F with 2 parameters that result from comparing G and A , and B and the constant 4 ? Or does it mean call F with the result of calling generic method G using type parameters A and B and an argument of 4 ?
F ( G < A , B > ( 4 ) ) ;
Generics and challenges on the Parser Front
C#
Take the standard return statement for a controller : is there a way to make this thing compile time safe ? using static reflection or some other trick ?
return View ( `` Index '' ) ;
Can you make Asp.net MVC View wireup compile time safe ?
C#
Consider the following types : The following does not compile : But the following does compile ( as I was surprised to discover ) : As I understand the compiler falls back to using the default == operator , which is defined on object and thus accepts any type for its arguments . The IL looks like this ( ignore the deta...
class A { } class B { } interface IC { } A a = null ; // the value does n't matter - null or anything else , for all threeB b = null ; IC c = null ; var x = a == b ; var x = a == c ; ldarg.0ldfld class A aldarg.0ldfld class IC cceqstloc.0
What 's the reasoning to fallback to Object 's == operator when one operand is an interface ?
C#
I 'm working on an assignment for school in which we make a small game using monogame , with the added challenge of working in F # . The game logic is fully immutable F # , and the entrypoint is in C # by use of the Game class in monogame . I have however come across a weird problem concerning Record types in F # . In ...
... module Vectors = type Vector = { x : double y : double } let Zero : Vector = { x=0.0 ; y=0.0 } ... ... player.vector = Vectors.Zero ; ...
Record instance in F # is null in C #
C#
I wonder why in a console app , if I spin a new thread to run from Main , even though Main will reach the end it will wait , though if I spin up a new task , it will exit and not wait for the task to end . e.g.vs .
static void Main ( string [ ] args ) { Thread t = new Thread ( new ThreadStart ( SomeMethod ) ) ; t.Start ( ) ; // Main will wait , and app wo n't close until SomeMethod finishes } static void Main ( string [ ] args ) { Task.Run ( ( ) = > SomeMethod ( ) ) ; // Main will close / app shuts down without waiting for SomeMe...
Why Main waits when spinning a new thread , but not so with a task
C#
I 'm learning C # and the best practices around it.Now that I know : Single Responsibility PrincipleStatic classSingletonDependency InjectionEveryone said to avoid Singleton and Static , and prefer dependency injection instead.Now I have converted all of my classes so that they wo n't have to get their own data , such ...
_myItem = Repository.Instance.FindById ( 1 ) ; public MyClass ( Repository repository ) { _myItem = repository.FindById ( 1 ) ; }
Where is the root of all ( OOP ) dependencies stored ?
C#
I have the list of objects of the following class , The invoice numbers can be duplicate or there can even be a case of 4 invoices , all with the same number . I need to set the IsDupe flag on all except one of the invoice object.One approach is the brute force method of having a list of invoice numbers and comparing e...
class Invoice { public int InvoiceNumber ; public string CustomerName ; public bool IsDupe ; }
Flag all but one duplicates in a list
C#
If I have a Stack < T > for some T , and round-trip it to JSON using the new System.Text.Json.JsonSerializer , the order of the items in the stack will be reversed after deserialization . How can I serialize and deserialize a stack to JSON using this serializer without this happening ? Details as follows . I have a Sta...
[ 3,2,1 ] var stack = new Stack < int > ( new [ ] { 1 , 2 , 3 } ) ; var json = JsonSerializer.Serialize ( stack ) ; var stack2 = JsonSerializer.Deserialize < Stack < int > > ( json ) ; var json2 = JsonSerializer.Serialize ( stack2 ) ; Console.WriteLine ( `` Serialized { 0 } : '' , stack ) ; Console.WriteLine ( json ) ;...
How can I serialize a Stack < T > to JSON using System.Text.Json without reversing the stack ?
C#
Hi I 'm working with the mvc 5 framework in ASP.Net on a course I 'm taking at my school , but I seem to have hit a wall.I want to go back and add a field value to my main model ( Student ) class , but of course that means the structure of the database has to change ( getting errors when I try to run it ) . I was told ...
PM > enable-migrations
Deleting and updating db after changing model class ?
C#
I found something that I do not really get : Suppose the `` body '' is empty - If I remove the condition in the DrawChar , the program never draws anything and I found out that the onPaint is not even raised anymore ( e.g . when resizing or minimazing and restoring the window ) . EDIT : The point is - if the DrawImage ...
protected override void OnPaint ( PaintEventArgs e ) { DrawChar ( e.Graphics ) ; base.OnPaint ( e ) ; } void DrawChar ( Graphics g ) { if ( body ! = null ) { g.DrawImage ( body , X , Y ) ; } }
Why OnPaint is not called anymore if it fails to load a picture once ?
C#
I have been struggling with something that I found out to be very weird . Obviously , C # behaves this way but I was wondering how to prevent it . My code is very long so I 've made a small example of my dilemma : In the code above , my printings say : Those values is to me right , but they should be stored in the bank...
using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace WindowsFormsApplication4 { public partial class Form1 : Form { private List < Person > ...
Wrong variable getting updated
C#
I am trying to write a Generic Base Service Class where after receiving the fist generic list of data as the actual type of Db Model Entity need a conversion to a new Generic View Model type of data . I have tried list.ConvertAll ( ) but always getting a build error for ConvertAll ( ) method.I also tried list.Cast < TV...
public abstract class Entity { [ Key ] [ Index ( `` IX_Id '' , 1 , IsUnique = true ) ] public string Id { get ; set ; } [ DataType ( DataType.DateTime ) ] public DateTime Created { get ; set ; } public string CreatedBy { get ; set ; } [ DataType ( DataType.DateTime ) ] public DateTime Modified { get ; set ; } public st...
How to Convert a generic type list of data to another generic type list of data
C#
I have litle problem . I 'm a new dev and I have view with `` Age criterion '' for my product . These options are : `` < 24 '' , `` 24 - 35 '' , `` 35 - 45 '' , `` > 45 '' .A json which I need to work looks that : My View model : And my domain model : So here is my problem . I need to map viewmodel to domain model . Bu...
`` age '' : { `` lessThan24 '' : true , `` between24And35 '' : true , `` between35And45 '' : true , `` moreThan45 '' : true } public class AgeCriterionViewModel { public bool ? LessThan24 { get ; set ; } public bool ? Between24And35 { get ; set ; } public bool ? Between35And45 { get ; set ; } public bool ? MoreThan45 {...
Four nullable boolean multiple choice checkboxs .
C#
I want to convert IEnumerable < Task < T > > to IObservable < T > . I found solution to this here : It is perfectly ok for usual cases , but I need to handle exceptions , that could raise in that Tasks ... So IObservable < T > should not be dead after first exception.What I read , recommendation for this use case is to...
IObservable < T > ToObservable < T > ( IEnumerable < Task < T > > source ) { return source.Select ( t = > t.ToObservable ( ) ) .Merge ( ) ; } IObservable < Either < T , Exception > > ToObservable < T > ( IEnumerable < Task < T > > source ) { var subject = new Subject < Either < T , Exception > > ( ) ; foreach ( var obs...
Convert IEnumerable < Task < T > > to IObservable < T > with exceptions handling
C#
SolvedSeems that Oliver is right . After Several tries I got the exception and in debug mode i get it for sure . So this has to be all about timing . You should also check Matthew wattsons answer ; ) ExampleFirst of all a little example that shall explain my confusion.QuestionSo now my question : if I uncomment label1....
using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.Threading ; namespace testCrossThreading { public partial class Form1 : Form { public Form1 ( ) { InitializeCompone...
Why does Crossthreading work this way ?
C#
I 'm trying to break down this string into 2 colours and wondered if there is a neater way of achieving the same result ?
// Obtain colour valuesstring cssConfig = `` primary-colour : Red , secondary-colour : Blue '' ; var parts = cssConfig.Split ( ' , ' ) ; var colour1 = parts [ 0 ] .Split ( ' : ' ) [ 1 ] ; var colour2 = parts [ 1 ] .Split ( ' : ' ) [ 1 ] ;
What is a more efficient / tidier way of breaking this string down ?
C#
This happens in both C # and Java so I think it 's not a bug , just wonder why.According to this page , the lower case of `` '' is `` '' , they should be the equal when comparing with IgnoreCase option . Why they are not equal ?
var s = `` '' ; var lower = s.ToLower ( ) ; var upper = s.ToUpper ( ) ; if ( ! lower.Equals ( upper , StringComparison.OrdinalIgnoreCase ) ) { //How can this happen ? }
Case-insenstive string comparison strange behavior
C#
Possible Duplicate : passing an empty array as default value of optional parameter in c # This code is correct in C # 4.0but when applied on arrays it gives me errorsCould anyone show me the right way ? 10x
static void SomeMethod ( int x , int y = 5 , int z = 7 ) { } SomeMethod ( 1 ) ; private static void diagonalFill ( int [ , ] a , int [ ] fillType = { 0 , -1 } , int [ ] diagFill = { -1,1 } ) { } diagonalFill ( array ) ;
set initialized arrays as parameters in C #
C#
I am tired of writing : or : So I was hope to shorten this snippet , to something like this : it is pretty match the same length but usually there are few objects to check and adding params as parameter can shorten : to : Basically function IfNull have to get access to function one step higher in stack trace and finish...
if ( objectA ! =null ) return ; if ( objectB==null ) return ; Returns.IfNull ( objectA ) ; if ( objectA==null || objectB ! =null || objectC ! =null ) return ; Returns.IfNull ( objectA , objectB , objectC ) ;
Finish function higher in hierarchy
C#
This contrived example is roughly how my code is structured : Now I 'm trying to build a collection that would hold multiple SuperHero objects and offer a AllHerosFightCrime method . The hero 's should not all fight at once ( the next one starts when the first is finished ) .How can I return the IObservable < CrimeFigh...
public abstract class SuperHeroBase { protected SuperHeroBase ( ) { } public async Task < CrimeFightingResult > FightCrimeAsync ( ) { var result = new CrimeFightingResult ( ) ; result.State = CrimeFightingStates.Fighting ; try { await FightCrimeOverride ( results ) ; } catch { SetError ( results ) ; } if ( result.State...
Can not return IObservable < T > from a method marked async
C#
I have following xml : in other standard xml like this question here we have no problem but in php web service : http : //sandoghche.com/WebServicefor inbox check my inbox xml is this : for this I wrote the following codeand this codebut ca n't catch values on this xml document.Is there a clean way to do this ?
< ? xml version=\ '' 1.0\ '' encoding=\ '' UTF-8\ '' ? > < Result > < text_message > < id > 509 < /id > < message > < ! [ CDATA [ a ] ] > < /message > < time > 1323519941 < /time > < message_phone > < cellphone > 09196070718 < /cellphone > < /message_phone > < /text_message > < text_message > < id > 507 < /id > < messa...
access sub XML values in sms web service that hasnt value in standard way
C#
The examples that I have come across for when `` new '' makes sense involve maintenance situations where the sub class is inheriting from a base class in a library , and a new version of the library adds a method with the same name as one that has been implemented in the sub class . ( See : Brittle Base Classes ) What ...
public class FruitBasket { public int Weight { get ; set ; } public List < Fruit > Fruits { get ; set ; } } public class AppleBasket : FruitBasket { public new List < Apple > Fruits { get ; set ; } }
Are there situations when new should be used instead of override when you control the base class ?
C#
We have a newly set-up CRM 2015 On-Premise environment ; and we 're doing some fiddling with the Social Care framework.We simply wanted to update a Social Profile record 's InfluenceScore parameter within our custom application using a web service call , but it appears to have no effect on the field . Oddly enough , it...
// Retrieving the social profile record with all it 's columnsEntity socialProfile = GetSocialProfileByName ( socialProfileName ) ; double score = 0 ; string scoreField = `` influencescore '' ; // If socialProfile contains our attribute , set it appropriately , otherwise add the attributeif ( socialProfile.Contains ( s...
Can not update InfluenceScore on Social Profiles programmatically
C#
With C # , we now can have optional parameters , and give them default values like this : Now , suppose in the interface we derive from , we haveSee , that the default value is defined as different in the base class as in the interface . This is really confusing , as now the default value depends whether I doorWhy is i...
public abstract class ImporterBase : IImporter { public void ImportX ( bool skipId = true ) { // ... . } } public interface IImporter { void ImportX ( bool skipId = false ) ; } IImporter interfaceImporter = new myConcreteImporter ( ) ; //which derives from ImporterBaseinterfaceImporter.DoX ( ) ; //skipId = false Import...
C # optional parameters : Why can I define the default different on interface and derived class ?
C#
Possible Duplicate : Why use “ new DelegateType ( Delegate ) ” ? What is the difference between new Thread ( void Target ( ) ) and new Thread ( new ThreadStart ( void Target ( ) ) ) ? So I have been through a little bit of delegate and got the whole idea somehow . Now , I see everywhere exemple like this : I would thin...
public delegate void Deleg ( ) ; Deleg deleg = new Deleg ( FunctionName ) ; deleg ( ) ; public delegate void Deleg ( ) ; public Deleg deleg ; deleg = FunctionName ; deleg ( ) ;
Differences with delegate declaration in c #
C#
I have an AddressBook controller that will return a list of `` folders '' ( basically groups / locations ) . This may be called via an AJAX request or within a MVC page itself at render time.How can I create a function that will work well for both scenarios ? Here is my current Controller action which I seem to struggl...
public ActionResult GetFolderList ( int ? parent ) { List < String > folderList = new List < String > ( ) ; folderList.Add ( `` East Midlands '' ) ; folderList.Add ( `` West Midlands '' ) ; folderList.Add ( `` South West '' ) ; folderList.Add ( `` North East '' ) ; folderList.Add ( `` North West '' ) ; return Json ( fo...
How to create an ActionController to work both at run time and with ajax
C#
I have a ToolBar with 3 DataTemplates for my Items : The ItemsSource is a ObservableCollection < object > The first three items are already available in the constructor of my ViewModel , those three use the DataTemplates as expected.If I add another `` SimpleContextActionViewModel '' to the ObservableCollection , the T...
< ToolBar ItemsSource= '' { Binding ContextActions } '' Background= '' Transparent '' ToolBarTray.IsLocked= '' True '' > < ToolBar.Resources > < DataTemplate DataType= '' { x : Type viewModels : SimpleContextActionViewModel } '' > < Button Command= '' { Binding ActionCommand } '' Style= '' { StaticResource ToolBarButto...
ObservableCollection.CollectionChanged does not select the correct DataTemplate on ToolBar
C#
I 'm trying to build a generic class whose constructor introduces an additional type , but the compiler says no-no.I do n't quite understand why the following does n't work : It 's not critical as I can write the class using a fluent api ( which might be preferred ) , but I 'd still like to understand why I ca n't . Th...
public class Foo < T > { public Foo < T , TBar > ( TBar tBar ) { ... } }
Is it possible to have a constructor on a generic class that introduces additional generic types ?
C#
I have a WriteableBitmap which I use an unsafe method to plot pixels . The essential part looks like this : However , it is not certain that what the user wants to plot is of the type byte , and it would make sense to make this method generic ( i.e . DrawBitmap < T > ) but how can I make the pointer pPixels of type T* ...
private unsafe void DrawBitmap ( WriteableBitmap bitmap , byte [ ] pixels ) { // Boilerplate omitted ... fixed ( byte* pPixels = pixels ) { for ( int y = 0 ; y < height ; y++ ) { var row = pPixels + ( y * width ) ; for ( int x = 0 ; x < width ; x++ ) { * ( row + x ) = color [ y + height * x ] ; } } } bitmap.WritePixels...
How can I make a pointer generic in C # ?
C#
Today I discovered something strange . I wonder why this works : Think about it : What is the result when you call ExampleMethod ( 3 ) ; In my opinion it leads to an unpredictable result . In my case always Method 1 was called . But as I changed the signature of Method 1 , the Main Method called Method 2 ( of course ) ...
static void Main ( string [ ] args ) { Console.WriteLine ( ExampleMethod ( 3 ) ) ; Console.ReadKey ( ) ; } public static string ExampleMethod ( int required , params int [ ] optionalint ) { return `` ExampleMethod 2 '' ; } public static string ExampleMethod ( int required , string optionalstr = `` default string '' , i...
C # method overload with params and optionals
C#
I 'm doing a little c # project where im programming a little game , just to get better and convident with c # . The game is about a hero and I want to display the stats of the hero in a listbox . I 've get and set methods for every variable , but if I want to add them to a string , it ' simply adds `` '' or 0 for the ...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Game { class Hero : Character { int health , max_health , dmg , gold , rüstung ; string name ; public Hero ( string name , int health , int max_health , int dmg , int rüstung , int gold ) :...
Getting sting variables out of a class
C#
I 'm trying to fill some data into two arrays , one containing normalized angles and another containing the sin of those angles . The arrays have to be 2D because they 're going to be passed into a function that trains a neural network . I 'm tried declaring a [ 1 ] [ 360 ] array and got errors , so I 've also tried [ ...
double [ ] [ ] sin_in = new double [ 1 ] [ ] ; double [ ] [ ] sin_out = new double [ 1 ] [ ] ; double deg = 0.0 ; const double dtor = 3.141592654 / 180.0 ; for ( int i = 0 ; i < 360 ; i++ ) { sin_out [ 0 ] [ i ] = Math.Sin ( deg * dtor ) ; // complains I need to use new sin_in [ 0 ] [ i ] = deg / 360.0 ; //When I use n...
issue with 2D arrays
C#
I 've taken control of some entity framework code and am looking to refactor it . Before I do , I 'd like to check my thoughts are correct and I 'm not missing the entity-framework way of doing things.Example 1 - Subquery vs JoinHere we have a one-to-many between As and Bs . Apart from the code below being hard to read...
from a in dataContext.Aswhere ( ( from b in dataContext.Bs where b.Text.StartsWith ( searchText ) select b.AId ) .Distinct ( ) ) .Contains ( a.Id ) select a from a in dataContext.Aswhere a.Bs.Any ( b = > b.Text.StartsWith ( searchText ) ) select a from a in dataContext.Asjoin b in dataContext.Bs on b.AId equals a.Idjoi...
Data layer refactoring
C#
I am new to c # and need help understanding what going on in the following functionwhere table is a Dictionary . I can see that is is recursive but how is parse being passed three params when it is defined to take just a string ? EDIT : how do I delete a question ? parse has been overloaded facepalm
public bool parse ( String s ) { table.Clear ( ) ; return parse ( s , table , null ) ; }
c # parameters question
C#
i did 2 basic tests1-Resultsresults mean Select faster than Set by one and half time exactly by 142.78 % 2-Resultsresults means they are the same that 's mean if you need to set one variable prefer to use Select cuz in the future if you want to set another one just , @ w=3 will be added but if you want to set more than...
Create Procedure [ dbo ] . [ SetLoop ] As Begin declare @ counter int = 0 , @ a int , @ b int , @ c int , @ d int , @ e int While @ counter < 1000000 Begin set @ a=1 set @ b=2 set @ c=3 set @ d=4 set @ e=5 set @ counter = @ counter + 1 EndEnd create procedure SelectLoopAs Begin declare @ counter int =0 , @ a int , @ b ...
Why Select faster than Set statement
C#
My data table contains all string columns but in some columns we are filling numeric values . when I do orderby on datatable of that numeric column , it is not ordering properly . before order my table looksafter order it looks likeMy code :
Name Account DepartmentKiran 1100 CSCSubbu 900 CSCRam 500 CSCRaj 800 CSCJoy 400 CSC Name Account DepartmentKiran 1100 CSCJoy 400 CSCRam 500 CSCRaj 800 CSCSubbu 900 CSC public DataTable sortData ( string columnName ) { DataTable dt1=new DataTable ( ) ; return dt1=dataMgr [ DatabaseFileNames.ControlDatabase ] [ `` Ordere...
Convert to decimal and do OrderBy
C#
So I have the following code : And in the main method I have : My question is why the variable p1 has type Color ( isColor is true ) if in the clone method I cast the result to ColorPrototype ( return this.MemberwiseClone ( ) as ColorPrototype ; ) ? Reference : http : //www.dofactory.com/net/prototype-design-pattern
/// < summary > /// The 'Prototype ' abstract class/// < /summary > abstract class ColorPrototype { public abstract ColorPrototype Clone ( ) ; } /// < summary > /// The 'ConcretePrototype ' class/// < /summary > class Color : ColorPrototype { private int _red ; private int _green ; private int _blue ; // Constructor pu...
strange behaviour of `` as '' operator
C#
Was there any shortcut in c # that would allow to simplify this : and into something like this : I know it 's possible to assign properties during declaration like this : It would be interesting to know if there are other useful shortcuts like that , but I ca n't find any .
List < string > exampleList = new List < string > ( ) ; exampleList.Add ( `` Is '' ) ; exampleList.Add ( `` it '' ) ; exampleList.Add ( `` possible '' ) ; var exampleList = new List < string > ( ) ; exampleList { .Add ( `` is '' ) ; .Add ( `` it '' ) ; .Add ( `` possible '' ) ; } var myObject = new MyObject { Id = `` U...
c # syntax shortcut to skip an object name when refering to it multiple times in a row
C#
I 'm building a list of strings that contains all permutations of 2-letter strings , for instance `` aa '' to `` zz '' . This is what I have : Basically , it 's a loop inside a loop that combines characters from the alphabet . Now suppose I want to include NumberOfChars as a parameter that determines the length of each...
public List < string > SomeMethod ( int NumberOfChars ) { for ( var i = 0 ; i < 26 ; i++ ) { char character1 = ( char ) ( i + 97 ) ; var Letter1 = character1.ToString ( ) ; for ( var j = 0 ; j < 26 ; j++ ) { char character2 = ( char ) ( j + 97 ) ; var Letter2 = character2.ToString ( ) ; string TheString = Letter1 + Let...
Number of loop recursions as a parameter
C#
The following C # program produces unexpected output . I would expect to see : Value1 : 25 , Value2 : 10Value1 : 10 , Value2 : 25but instead I seeValue1 : 0 , Value2 : 10Value1 : 10 , Value2 : 25Can somebody explain to me why it is that using the `` await '' operator in the expression for the second argument to the Pri...
namespace ConsoleApplication4 { class Program { static void Main ( string [ ] args ) { DoWork ( ) .Wait ( ) ; Console.ReadLine ( ) ; } private async static Task DoWork ( ) { SomeClass foo = new SomeClass ( ) { MyValue = 25.0f } ; PrintTwoValues ( foo.MyValue , await GetValue ( ) ) ; PrintTwoValues ( await GetValue ( ) ...
Why does using the await operator for the second argument to a method affect the value of the first argument ?
C#
I have a lot of methods that follow in large parts the same algorithm , and I ideally want to be able to make calls to a generic method that eliminates a lot of code duplication.I have tons of methods like the ones below , I would optimally want to be able to just call Save < SQLiteLocation > ( itemToSave ) ; but i hav...
public bool SaveLocation ( ILocation location , ref int primaryKey ) { var dbConn = new SQLiteConnection ( dbPath ) ; SQLiteLocation itemToSave = new SQLiteLocation ( ) ; itemToSave.LocationName = location.LocationName ; itemToSave.Latitude = location.Latitude ; itemToSave.Longitude = location.Longitude ; itemToSave.Pr...
Troubles with large amount of Code duplication
C#
I recently introduced an interface on a base class for unit-testing purposes and ran into a weird problem . This is the minimal reproducible scenario : The output of the first two Console.WriteLine commands is logical , but I fail to accept the output of the last one , it even outputs Child when using a temporary varia...
interface IBase { string Text { get ; } } interface IChild : IBase { } class Base : IBase { public string Text { get { return `` Base '' ; } } } class Child : Base , IChild { public new string Text { get { return `` Child '' ; } } } static void Main ( string [ ] args ) { var child = new Child ( ) ; Console.WriteLine ( ...
Interface inheritance and property hiding trouble
C#
Let 's say I have some component like this : Who is responsible for calling Dispose on the example control ? Does removing it from this.Controls cause it to be disposed ? Or does this leak bunches of window handles backing the controls ? ( For reference , I 'm asking this because I do n't see where the Windows Forms De...
class SomeForm : Form { private Control example ; public void Stuff ( ) { this.example = new ComboBox ( ) ; // ... this.Controls.Add ( example ) ; } public void OtherStuff ( ) { this.Controls.Remove ( example ) ; } }
Who owns controls ?