lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
If I attempt to write two overloads of a method , one accepting an Expression < Func < T > > parameter and another accepting a Func < T > , I will get a compiler error on trying to call the method with a lambda expression because the two signatures create ambiguity . The following would be problematic , for example : I...
Method ( ( ) = > `` Hello '' ) ; // Is that a Func < string > , // or is it an Expression < Func < string > > ? Method ( ( ) = > `` Hello '' ) ; Executed ' ( ) = > `` Hello '' ' and got `` Hello '' back . Method ( ReturnHello ) ; Executed 'ReturnHello ' and got `` Hello '' back .
Can I define a method to accept EITHER a Func < T > OR an Expression < Func < T > > ?
C#
This is strange.I have a windows application that dynamically loads DLLs using Reflection.Assembly.LoadFrom ( dll_file_name_here ) .It works as expected , until I ILMerge the application with another DLL.So this scenario works fine : MyApp.exeMyAppComponent.dllPlugin.dllOnce I ILMerge MyApp.exe and MyAppComponent.dll r...
foreach ( typeAsm in Reflection.Assembly.LoadFrom ( `` Plugin.dll '' ) )
Dynamic loading working fine , except after the executable is ILMerged
C#
I have a bunch of SKUs ( stock keeping units ) that represent a series of strings that I 'd like to create a single Regex to match for.So , for example , if I have SKUs : ... I 'd like to automatically generate the Regex to recognize any one of the SKUs.I know that I could do simply do `` BATPAG003|BATTWLP03|BATTWLP04|...
var skus = new [ ] { `` BATPAG003 '' , `` BATTWLP03 '' , `` BATTWLP04 '' , `` BATTWSP04 '' , `` SPIFATB01 '' } ; BATPAG003|BATTWLP03|BATTWLP04|BATTWSP04|SPIFATB01BAT ( PAG003|TW ( LP0 ( 3|4 ) |SP04 ) ) |SPIFATB01BAT ( PAG003|TW ( LP ( 03|04 ) |SP04 ) ) |SPIFATB01B ( ATPAG003|ATTW ( LP0 ( 3|4 ) |ATSP04 ) ) |SPIFATB01 Fu...
Generating the Shortest Regex Dynamically from a source List of Strings
C#
I want to call a constructor of a struct , that has default values for all parameters . But when I call the parameterless constructor of MyRectangle a not defined constructor get 's called . Why is that ? Is it possible to not have a not from me created constructor called ?
using System ; namespace UebungClasses { class Program { static void Main ( string [ ] args ) { MyRectangle sixRec = new MyRectangle ( 3 , 2 ) ; MyRectangle oneRec = new MyRectangle ( ) ; Console.WriteLine ( `` area of six : `` + sixRec.Area ( ) + `` area of one : `` + oneRec.Area ( ) ) ; } } public struct MyRectangle ...
Calling a constructor with default parameters instead of default constructor
C#
I have two classes Order and OrderDetail : They are mapped like this : When I create order and order details : Details of order empty there and OrderId of orderdetails is null also . When I add created order detail in context then it will be added to Details and OrderId becomes Id of created order . Why it works only w...
public class Order : Entity { public Order ( KitchenAppContext context ) : base ( context ) { } public Order ( ) : base ( ) { } public DateTime Date { get ; set ; } public Guid MenuId { get ; set ; } public virtual Menu Menu { get ; set ; } public bool IsClosed { get ; set ; } public decimal Price { get ; set ; } publi...
Why reference properties works only through context
C#
What is the equivalent c # generics notation of the above java generics ? Parameter listenerClass will be a type & not a object . But the object T has to belong to a specific hierachy .
public < T extends java.util.EventListener > T [ ] getListeners ( final Class < T > listenerClass ) { ... }
C # generics & not going insane
C#
Right now my code looks like this : Is there a more succinct way of creating a list in one line of code , with one element added optionally ?
var ids = projectId.HasValue ? new List < Guid > { projectId.Value } : new List < Guid > ( ) ;
C # collection initializer – is it possible to add an element optionally , based on a condition ?
C#
I get the following response from a webservice : How must the json-object look like to deserialize this ? Or is there another way to get the values of the properties ?
{ `` data '' : { `` foo.hugo.info '' : { `` path '' : `` logon.cgi '' , `` minVersion '' : 1 , `` maxVersion '' : 2 } , `` foo.Fritz.Task '' : { `` path '' : `` Fritz/process.cgi '' , `` minVersion '' : 1 , `` maxVersion '' : 1 } } , `` success '' : true }
How to make an c # object from json
C#
I am writing a short program which will eventually play connect four.Here it is so far , pastebinThere is one part which is n't working . I have a jagged array declared on line 16 : Which I think looks like this : when I do this board [ 5 ] [ 2 ] = '* ' I getinstead of what I 'd like : How it runs at the moment ( outpu...
char [ ] [ ] board = Enumerable.Repeat ( Enumerable.Repeat ( '- ' , 7 ) .ToArray ( ) , 7 ) .ToArray ( ) ; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -* -- -- ...
How to assign to a jagged array ?
C#
I have to zoom an image in uwp application , which works fine , but the design requires to have another image ( that works as a button ) in front of it and I dont want that element to be zoomed as well . It has to be only the image inside the canvas tag , this is how I have it now . thats the xaml I have and which make...
< ScrollViewer MinZoomFactor= '' 1 '' ZoomMode= '' Enabled '' VerticalScrollBarVisibility= '' Auto '' HorizontalScrollBarVisibility= '' Auto '' > < RelativePanel HorizontalAlignment = `` Stretch '' > < Canvas x : Name= '' canvas '' > < Image Source = `` { Binding Test , UpdateSourceTrigger=PropertyChanged , Mode=TwoWay...
scrollviewer zoom only one element
C#
What is the best way to synchronize 2 sets of data via Binding ? Now my question is , when I receive an update from one collection ( e.g . Source.CollectionChanged event ) I need to call the custom TargetSetters , and ignore the events called which originated from my update.And also the other way , when the Target cust...
Target = Custom Setters - raises custom events whenever something changedSource = ObservableCollection - raises events whenever collection changed private void ObservableCollection_OnCollectionChanged ( object sender , NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs ) { CustomObject.SelectionChanged -...
TwoWay Collection Binding Sync/Lock
C#
After de-compiling the Linq IEnumerable extension methods I was glad to see thatthe Count ( ) method , prior to trying to iterate the whole enumerable , attempts to downcast it to an ICollection or an ICollection < T > e.g : Why is n't this happening in Any ( ) ? wo n't it benefit from using .Count > 0 instead of creat...
public static int Count < TSource > ( this IEnumerable < TSource > source ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; ICollection < TSource > collectionoft = source as ICollection < TSource > ; if ( collectionoft ! = null ) return collectionoft.Count ; ICollection collection = source as IColle...
In IEnumerable extensions - why is only Count ( ) optimized for ICollection ?
C#
I have the following method that takes in a details object , validates it , converts it to a request and enqueues it . Everything is fine apart from the validate request which I am having trouble with . Basically , there is different validation logic for each different details object . I know from the generic constrain...
private void Enqueue < TDetails , TRequest > ( TDetails details ) where TDetails : BaseDetails where TRequest : BaseRequest { bool isValid = _validator.Validate ( details ) ; if ( isValid ) { TRequest request = ObjectMapper .CreateMappedMessage < TDetails , TRequest > ( details ) ; _queue.Enqueue ( request ) ; } }
Newbie polymorphism question using generics
C#
What if I had something like this : Now as we can see , I 'm trying to handle exceptions for some different cases . BUT whenever an exception is raised , I 'm always calling the method DoSomething ( ) at the end . Is there a smarter way to call DoSomething ( ) if there is an exception ? If I added a finally block and c...
try { //work } catch ( ArgumentNullException e ) { HandleNullException ( ) ; Logger.log ( `` ArgumentNullException `` + e ) ; DoSomething ( ) ; } catch ( SomeOtherException e ) { HandleSomeOtherException ( ) ; Logger.log ( `` SomeOtherException `` + e ) ; DoSomething ( ) ; } catch ( Exception e ) { HandleException ( ) ...
A lot of catch blocks , but in all of them the same function
C#
I have columns list in which I need to assign Isselected as true for all except for two columns . ( Bug and feature ) . I have used this following code to achieve it and working fine , but is there any quick or easy way to achieve the same ? Thanks in advance
DisplayColumns.ToList ( ) .ForEach ( a = > a.IsSelected = true ) ; DisplayColumns.ToList ( ) .Where ( a = > a.ColumnName == `` Bug '' || a.ColumnName == `` Feature '' ) .ToList ( ) .ForEach ( a = > a.IsSelected = false ) ;
Optimize Linq in C #
C#
I am facing a strange issue , sometimes i am getting the url from the sendgrid ashttps : //localhost:81/Activation ? username=ats8 @ test.com & activationToken=EAAAAA which works fine . but sometimes i am getting url which is encoded as follows , '' https : //localhost:81/Activation ? username=ats8 % 40test.com & activ...
public class Verification { [ DataType ( DataType.EmailAddress ) ] public string Username { get ; set ; } [ Required ] [ DataType ( DataType.Password ) ] public string Password { get ; set ; } [ Required ] [ DataType ( DataType.Password ) ] [ Compare ( `` Password '' ) ] public string ConfirmPassword { get ; set ; } pu...
Why my ViewModel field becomes empty when the url is HTML encoded ?
C#
This code does n't look clean and this if condition can grow Is there any better solution to this problem ? Sadly that function is n't linear so it 's not easy to code that in a mathematical way .
public int VisitMonth ( int months ) { int visit = 0 ; if ( months < = 1 ) { visit = 1 ; } else if ( months < = 2 ) { visit = 2 ; } else if ( months < = 4 ) { visit = 3 ; } else if ( months < = 6 ) { visit = 4 ; } else if ( months < = 9 ) { visit = 5 ; } else if ( months < = 12 ) { visit = 6 ; } else if ( months < = 15...
Replacing if else statement with any design pattern or better approach
C#
I have problem to get image bytes data from oracle . reader ( `` image '' ) always returning 0 length . Is their any workaround ? If i used oledb then its working but not working with Microsoft EnterpriseLibrary .
using ( IDataReader reader = ExecuteNonQueryOracle ( Query ) ) { while ( reader.Read ) { dict ( `` image '' ) = reader ( `` image '' ) ; } } public object ExecuteNonQueryOracle ( string Query ) { using ( dbCommand == CurrentDatabase.GetSqlStringCommand ( Query ) ) { dbCommand.CommandType = CommandType.Text ; return Cur...
Obtaining LONG RAW Data ( Bytes ) from EnterpriseLibrary
C#
I just have started to design with DDD ( I have no experience neither a teacher ) I have some domain service classes that have to reference each other in some point . So I decided to inject the references through constructor.And when I created a view that has a lot of data to display in the controller I had to create a...
EmployeeRepository employRepository = new EmployeeRepository ( ) ; ShiftModelRepository shiftModelRepository = new ShiftModelRepository ( ) ; ShiftModelService shiftModelService = new ShiftModelService ( shiftModelRepository ) ; EmployeeService employeeService = new EmployeeService ( employRepository , shiftModelServic...
Is it a good design practice to have an interface for each service class in DDD ?
C#
Hello everyone i 'm new to c # language i was use vb.net , in below what is the error with this code and why , thank youbut when i try this code to c # i get Errorerror : Property or indexer ‘ Example.splitstring.current ’ can not ve assigned to – it is read only
vb.net codeClass SplitStringImplements IEnumerableImplements IEnumeratorPrivate currentPosition As Integer = 0Private m_Sentence As StringProperty Sentence ( ) As String Get Return m_Sentence End Get Set ( ByVal Value As String ) m_Sentence = Value Me.Reset ( ) End SetEnd PropertyPublic ReadOnly Property Current As Obj...
IEnumerator IEnumerable vb to C #
C#
The title suggests that i 've already an idea what 's going on , but i can not explain it . I 've tried to order a List < string [ ] > dynamically by each `` column '' , beginning with the first and ending with the minimum Length of all arrays.So in this sample it is 2 , because the last string [ ] has only two element...
List < string [ ] > someValues = new List < string [ ] > ( ) ; someValues.Add ( new [ ] { `` c '' , `` 3 '' , `` b '' } ) ; someValues.Add ( new [ ] { `` a '' , `` 1 '' , `` d '' } ) ; someValues.Add ( new [ ] { `` d '' , `` 4 '' , `` a '' } ) ; someValues.Add ( new [ ] { `` b '' , `` 2 '' } ) ; someValues = someValues...
For-Loop and LINQ 's deferred execution do n't play well together
C#
What are the implications of doing this ... ... versus this ? I suspect that the compiler is creating a new instance for me in the second example . I 'm sure this is a bit of a newbie question , but Google did n't turn up anything . Can anyone give me some insight ?
this.myButton.Click += new EventHandler ( this.myButton_Clicked ) ; this.myButton.Click += this.myButton_Clicked ;
Should I Create a New Delegate Instance ?
C#
I am trying to open a proxy on a thread ( in background ) , the thread makes a new instance of the proxy , calls a method of the service and immediately after disposes the service.All of this happens on a thread : I keep seeing intermittent timeout issues happening even though I have set the timeout to max for CloseTim...
var background = new Thread ( ( ) = > { var proxy = new AssignmentSvcProxy ( new EndpointAddress ( worker.Address ) ) ; try { proxy.Channel.StartWork ( workload ) ; proxy.Dispose ( ) ; } catch ( EndpointNotFoundException ex ) { logService.Error ( ex ) ; proxy.Dispose ( ) ; proxy = null ; } catch ( CommunicationExceptio...
Starting multiple services on threads
C#
Just wondering why Expression Blend outputs a path nested in two canvases ( rather than just one ) , I 've also seen some with 3 or more but still outputting just one path : Is there any way I can get rid of the extra nested canvases in expression blends outputs ?
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Canvas xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' x : Name= '' cross '' Width= '' 146.768 '' Height= '' 146.768 '' Clip= '' F1 M 0,0L 146.768,0L 146.768,146.768L 0,146.768...
Multiple nested canvases in Expression Design xaml output , why ?
C#
I use this code And get true result : But when i try to lower : object text2 = `` test '' .ToLower ( ) ; i get false result ?
object text1 = `` test '' ; object text2 = `` test '' ; Console.WriteLine ( `` text1 == text2 : `` + ( text1 == text2 ) ) ; //return : true object text1 = `` test '' .ToLower ( ) ; object text2 = `` test '' .ToLower ( ) ; Console.WriteLine ( `` text1 == text2 : `` + ( text1 == text2 ) ) ; //return : false
How to compare two object which have string values ?
C#
Is there a way to create a strongly typed controller action ? For example : In a Controller I use : I would like to use : I do not want to re-invent the wheel . I am sure someone has some clever solution . This would allow me to add compile time checking to controller methods .
aClientLink = Url.Action ( `` MethodName '' , `` ControllerName '' , new { Params ... } ) ; aClientLink = Url.Action ( Controller.MethodName , ControllerName ) ;
Compile-time checking for action links to controller methods
C#
Code to illustrate : Now , `` DoSomethingWithStruct '' fails to compile with : `` Operator '== ' can not be applied to operands of type 'MyStruct ' and ' < null > ' '' . This makes sense , since it does n't make sense to try a reference comparison with a struct , which is a value type.OTOH , `` DoSomethingWithDateTime ...
public struct MyStruct { public int SomeNumber ; } public string DoSomethingWithMyStruct ( MyStruct s ) { if ( s == null ) return `` this ca n't happen '' ; else return `` ok '' ; } private string DoSomethingWithDateTime ( DateTime s ) { if ( s == null ) return `` this ca n't happen '' ; // XX else return `` ok '' ; }
c # `` == '' operator : compiler behaviour with different structs
C#
Is there any language which has a form of code templating ? Let me explain what I mean ... I was working on a C # project today in which one of my classes was very repetitive , a series of properties getters and setters.I realize that this could break down into basically a type , a name , and a default value.I saw this...
public static int CustomerID { get { return SessionHelper.Get < int > ( `` CustomerID '' , 0 ) ; // 0 is the default value } set { SessionHelper.Set ( `` CustomerID '' , value ) ; } } public static int BasketID { get { return SessionHelper.Get < int > ( `` BasketID '' , 0 ) ; // 0 is the default value } set { SessionHe...
Is there any language out there which uses code templating ?
C#
Is it possible to assign an attribute on a property and use it in order to assign other attributes - doing so without using reflection ? The code : I would like to do something like this :
public class CashierOut : BaseActivity { [ Description ( `` Flag indicates whether break to execution . '' ) ] [ DefaultValue ( false ) ] [ MyCustomAttribute ( ParameterGroups.Extended ) ] public bool CancelExecution { get ; set ; } [ Description ( `` Flag indicates whether allow exit before declation . '' ) ] [ Defaul...
C # Attributes : One Attribute to Rule Them All ?
C#
I have to save 2 different groups of settings in my root settings group . It should looks like this : The Nuance is that I have to save it one after another in different places in my code . ( For example , GROUP_1 can be a connection strings and GROUP_2 is some environment settings and they both together are filling by...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_1 '' > ... ... ... ... ... ... ... ... some_settings ... ... ... ... ... ... ... ... < /sectionGroup > < sectionGroup name= '' GROUP_2 '' > ... ... ... ... ... ...
App.config add nested group to existing node
C#
I have the following XML data . I need to present them on ASP.NET web page in a hierarchical tabular format.XML : Expected Output : where ( - ) is tree view 's expand/collapse control . Is it possible to achieve this using ASP.NET Data Grid ? Any code example would be really useful .
< Developers > < Region name= '' UK '' > < Region name= '' England '' > < Region name= '' London '' > < Data Date= '' 01-01-2019 '' > < Value name= '' DotNet '' > 100 < /Value > < /Data > < Data Date= '' 01-01-2020 '' > < Value name= '' DotNet '' > 200 < /Value > < Value name= '' Java '' > 300 < /Value > < /Data > < /R...
Show hierarchical xml data using ASP.NET Grid
C#
I am curious why the following throws an error message ( text reader closed exception ) on the `` last '' assignment : However the following executes fine : What is the reason for the different behavior ?
IEnumerable < string > textRows = File.ReadLines ( sourceTextFileName ) ; IEnumerator < string > textEnumerator = textRows.GetEnumerator ( ) ; string first = textRows.First ( ) ; string last = textRows.Last ( ) ; IEnumerable < string > textRows = File.ReadLines ( sourceTextFileName ) ; string first = textRows.First ( )...
Why does IEumerator < T > affect the state of IEnumerable < T > even the enumerator never reached the end ?
C#
How can I make a linq search that ignores nulls ( or nullables ) ? I have a method And I want it to return matches on any of the ints ? that are not null.IE : if a and c have values 1 and 9 and b is null the search should render ( roughly ) toMy real method will have 5+ paramters , so iterating combinations is right ou...
IEnumerable < X > Search ( int ? a , int ? b , int ? c ) SELECT * FROM [ TABLE ] WHERE a = 1AND c = 9
Linq search that ignores nulls
C#
I have a problem with my code where I try to save a many to many connection between two objects , but for some reason it does n't get saved.We used the code first method to create our database , in our database we have the following entities where this problem is about : The table ProductTagProducts got automatically c...
public class Product { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < ProductTag > ProductTags { get ; set ; } } public class ProductTag { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Product > Products { get ; set ; } } Pro...
No new many to many connections are made in the database when saving an object in EF
C#
Short version : how does async calls scale when async methods are called thousands and thousands of times in a loop , and these methods might call other async methods ? Will my threadpool explode ? I 've been reading and experimenting with the TPL and Async and after reading a lot of material I 'm still confused about ...
// an array with 5000 urls.var urls = new string [ 5000 ] ; // list of awaitable tasks.var tasks = new List < Task < string > > ( 5000 ) ; HttpClient httpClient ; foreach ( string url in urls ) { tasks.Add ( httpClient.GetStringAsync ( url ) ) ; } await Task.WhenAll ( tasks ) ; ... same variables as code A ... foreach ...
Async/Await regarding system resources consumption and efficiency
C#
This project is for educational use and I am very well aware that excellent compilers already exist.I am currently fighting my way through the famous Dragon Book and just started to implement my own Lexer . It works suprisingly well except for literals . I do not understand how to handle literals using symbol ( lookup ...
int myIdentifier = 60 ; < enum TokenType , int lookupIndex > //TokenType could be 'number ' and lookupIndex could be any int Dictionary < int literal , int index > //literal could be '60 ' and index could be anything
C # Dragon Book ( Lexical analysis ) How to handle literals
C#
I am replacing the html on my page when I return dynamically generated html from a REST method called via Ajax like so : It is called from within the ready function ( when a button is clicked ) like so : The string named `` HtmlToDisplay '' ( `` returneddata '' in the Ajax call ) begins like so : As you can see , it do...
[ HttpGet ] [ Route ( `` { unit } / { begdate } / { enddate } '' , Name = `` QuadrantData '' ) ] public HttpResponseMessage GetQuadrantData ( string unit , string begdate , string enddate ) { _unit = unit ; _beginDate = begdate ; _endDate = enddate ; string beginningHtml = GetBeginningHTML ( ) ; // This could be called...
Why does Chrome slap a body at the top of my HTML , and then give me a seemingly bogus err msg ?
C#
I have a loop variable that does not appear to be getting garbage collected ( according to Red -- Gate ANTS memory profiler ) despite having gone out of scope.The code looks something like this : As far as I can tell , a reference to item remains until blockingQueue.dequeue ( ) returns . Is this intended behaviour , or...
while ( true ) { var item = blockingQueue.dequeue ( ) ; // blocks until an item is added to blockingQueue // do something with item }
Loop variable not getting collected
C#
I 'm getting a strange error with Visual Studio 10 ( and now 11 as well ) . I have an extension methodNow if I callI 'm not at all understanding what 's happening under hood . The annoying part is that the intellisense lists Foo for IEnumberable < T > s . At best it should have given a type ca n't be inferred error.If ...
public static S Foo < S , T > ( this S s ) where S : IEnumerable < T > { return s ; } `` '' .Foo ( ) ; // = > 'string ' does not contain a definition for 'Foo ' and no extension method 'Foo ' accepting a first argument of type 'string ' could be found ( are you missing a using directive or an assembly reference ? ) Ext...
Can not find definition though intellisense lists it ?
C#
I 'm going to retrieve information from a database using LINQ but I do n't know why I 'm getting this error : Invalid object name 'Retriveinfos'.My class is here : and then using this line of code to connect and retrieving information :
[ Table ( Name= '' Retriveinfos '' ) ] public class Retriveinfo { [ Column ] public string Name { get ; set ; } [ Column ] public string LastName { get ; set ; } [ Column ( IsPrimaryKey = true ) ] public int Id { get ; set ; } } DataContext dcon = new DataContext ( @ '' Data Source=.\SQLEXPRESS ; AttachDbFilename=F : \...
Retrieving info from database
C#
I 'm taking an algorithm course at the university , and for one of my projects I want to implement a red-black tree in C # ( the implementation itself is n't the project , yet just something i decided to choose to help me out ) .My red-black tree should hold string keys , and the object i created for each node looks li...
class sRbTreeNode { public sRbTreeNode Parent = null ; public sRbTreeNode Right = null ; public sRbTreeNode Left = null ; public String Color ; public String Key ; public sRbTreeNode ( ) { } public sRbTreeNode ( String key ) { Key = key ; } } LeftRotate ( root , node ) y < - node.Right ; node.Right < - y.Left ; if ( y....
C # reference trouble
C#
The most efficient and typical solution that I could think of is : This will return me seven ( 7 ) dates in an array , which is the result I want . I think ruby can do something like this , simply by specifying dots but I ca n't recall.However , is there a more efficient approach ? Or is there any way to implement this...
var dates = new DateTime [ 7 ] ; for ( int i = 0 ; i < 7 ; i++ ) dates [ i ] = DateTime.Now.AddDays ( i ) ;
What are some ways to get a list of DateTime.Now.AddDays ( 0..7 ) dynamically ?
C#
I have done some search on this website to avoid duplication , however most of the questions were about an abstract comparison between interface and abstract class.My question is more to my specific situation especially my colleague and I we do n't agree about the same approach.I have 3 classesNode ( Abstract node in a...
public abstract class Node { public string Name { get ; set ; } public string FullName { get ; set ; } public Node Parent { get ; set ; } public List < PermissionEntry > Permissions { get ; set ; } protected Node ( string fullName ) { FullName = fullName ; Permissions = new List < PermissionEntry > ( ) ; } public void ...
Interface vs. Abstract class ( in specific case )
C#
I have text with this structure : I want to get this text : I tried doing the following but it does not workBasically , it should start matching at the start of every line and replace every matched group with # symbol . Currently , if more than one group is matched , everything is replaced by a single # symbol . Patter...
1 . Text12 . Text 2 . It has a number with a dot.3 . 1 . Text31 # Text1 # Text 2 . It has a number with a dot . ( notice that this number did not get replaced ) # # Text31 var pattern = @ '' ^ ( \s*\d+\.\s* ) + '' ; var replaced = Regex.Replace ( str , pattern , `` # '' , RegexOptions.Multiline ) ;
Regex replace any number of matches at the start of the line
C#
There are quite a few options available but none seem to be particularly designed for cases like this.i.e : UnauthorizedAccessException : I/OAccessViolationException : Memory stuffSecurityAccessDeniedException : Represents the security exception that is thrown when a security authorization request fails.etc.Should I cr...
[ WebService ( Namespace = `` http : //service.site.com/service/news '' ) ] [ WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 ) ] [ ToolboxItem ( false ) ] [ ScriptService ] public class NewsService : System.Web.Services.WebService { [ WebMethod ] [ ScriptMethod ] public void DoPost ( string title , string...
C # What exception should I raise here ?
C#
I have this code : How to get value of CustomAttribute for instance a ?
[ MyAttribute ( CustomAttribute= '' Value '' ) ] class MyClass { // some code } Main ( ) { MyClass a = new MyClass ( ) ; }
How to get attributes value
C#
I am uploading data to databases but my form upload the same data twice in databases first I was uploading data without checking weather is inserted or not it was working fine it was uploading the data single time now I have put the checked that if data inserted than show the message data inserted successful but this i...
SqlConnection conn1 = new SqlConnection ( `` Data Source=ZAZIKHAN\\SQLEXPRESS ; Initial Catalog=resume ; Integrated Security=True '' ) ; conn1.Open ( ) ; SqlCommand cmd3 = new SqlCommand ( `` insert into Profile ( Id , Name , JobTitle , Phone , Email , Address , Website , Facebook , Twitter , GooglePlus , Skype , Pictu...
Web form upload same data twice in database
C#
In C # , instances of reference types are passed to functions as a nullable pointer . Consider for example : In most cases , the function will expect a non-null pointer ( in 95 % of all cases in my experience ) . What is the best way to document the fact that this function expects a non-null pointer ? Update : thanks a...
public void f ( Class classInstanceRef )
How to document the `` non-nullableness '' of reference types in C # ?
C#
Why does the following cause a compilation error ? Note : The same error would occur if class XY : IX and where T : IX . However , I have chosen a more complex example because a simpler one might have provoked circumventive answers such as , `` Just change the type of xy from T to IX '' , which would not answer why thi...
interface IX { } interface IY { } class XY : IX , IY { } void Foo < T > ( ) where T : IX , IY { T xy = new XY ( ) ; … // ^^^^^^^^ } // error : `` Implicit conversion of type 'XY ' to 'T ' is not possible . ''
Why are conversions from `` class A : IX '' to generic `` T where T : IX '' not allowed ?
C#
I would like to write a static instance property in a base class and derive this , but I am facing some problems.Here is the code for the base class - I currently have : As you can see its primary use is for WPF Resources like Converts , where you normally declare a key in XAML thats static to get this instance also fo...
public abstract class ResourceInstance < T > { private static T _instance ; public static T Instance { get { if ( _instance ! = null ) return _instance ; var method = MethodBase.GetCurrentMethod ( ) ; var declaringType = method.DeclaringType ; if ( declaringType ! = null ) { var name = declaringType.Name ; _instance = ...
Static Instance Base/Derived class
C#
Or possibly there is a better way . I am building a dynamic query builder for NHibernate , we do n't want to put HQL directly into the application , we want it as ORM agnostic as possible . It looks like this currently : ok , great , however ... . there are two things in here that pose a problem : This query only handl...
public override IEnumerable < T > SelectQuery ( Dictionary < string , string > dictionary ) { string t = Convert.ToString ( typeof ( T ) .Name ) ; string criteria = string.Empty ; foreach ( KeyValuePair < string , string > item in dictionary ) { if ( criteria ! = string.Empty ) criteria += `` and `` ; criteria += item....
Can I pass in T.Property ? Also , ideas for improving this method ?
C#
Let 's say I have the following regex : Then I have the string : Here is my program : What I want to know is if there is any way to to get the regular expression part that matched ? In this case : I ca n't find it anywhere in the object , but one would think it would be accessible .
var r = new Regex ( `` Space ( ? < entry > [ 0-9 ] { 1,3 } ) '' ) ; `` Space123 '' void Main ( ) { Regex r = new Regex ( `` Space ( ? < entry > [ 0-9 ] { 1,3 } ) '' , RegexOptions.ExplicitCapture ) ; foreach ( Match m in r.Matches ( `` Space123 '' ) ) { m.Groups [ `` entry '' ] .Dump ( ) ; //Dump ( ) is linqpad to echo...
Get named group subpattern from .NET regex object
C#
What is the difference between two variable 's ToString Calling ? Does calling i.ToString ( ) will make i first boxed then call ToString or i is already boxed before calling ToString ( ) ?
int i = 0 ; i.ToString ( ) ;
difference between ValueType.ToString and ReferenceType.ToString
C#
I am trying to make a custom TabControl that supports scrolling but keeps the original look and feel of the TabControl , obviously with the exception that it scrolls.To begin I chose to edit a copy of the original template TabControl used.Then I put a ScrollViewer around the TabPanel . However , this has caused a minor...
< Window x : Class= '' ScrollableTabControl.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/mark...
XAML TabControl Border Issues
C#
I 'd like to write a Map-Extension Method for ParallelQuery without destroying the parallelism . Problem is , I have no idea how . I am using ParallelQuery because I 'm confident the Multithreading will boost my performance , here 's my code so far : As you can see , this kind of defeats the purpose of parallelism if I...
public static List < T2 > Map < T , T2 > ( this ParallelQuery < T > source , Func < T , T2 > func ) { List < T2 > result = new List < T2 > ( ) ; foreach ( T item in source ) { result.Add ( func ( item ) ) ; } return result ; }
How to write a Map-Method for ParallelQuery without defeating its purpose ?
C#
Solved : IntelliSense just does n't show the Extension ! Lets say we got the following extension method in F # : In C # I can call it like this way : But the equivalent VB code to this returns an error , it does n't find the extension method for the type integer : While it 's possible to call the method by the standard...
[ < Extension > ] module Extension = [ < Extension > ] let Increment ( value : System.Int32 ) = value + 1 x.Increment ( ) ; //Result x=1 x.Increment ( ) 'No method called `` Increment ( ) '' for type Int32 Increment ( x ) 'Works
Unable to call F # Extension in VB.Net
C#
Ok , I have this string Player.Character with this in it `` Average Man { [ Attributes ( Mind 10 ) ( Body 10 ) ( Soul 10 ) ] } '' . And I have this do-loop set up so that it should be going through this string 1 character at a time and seeing if its this `` [ `` while adding each character it checks to another string C...
int count = -1 ; string ContainerName = `` '' ; //Finds Start of containerdo { count = count + 1 ; ContainerName = ContainerName + Player.Character [ count ] .ToString ( ) ; } while ( Player.Character [ count ] .ToString ( ) ! = `` [ `` & & Player.Character.Length - 1 > count ) ; textBox1.Text = ContainerName ;
C # Do-Loop not adding Characters to a string
C#
I 'm currently working on a web application in asp.net . In certain api-calls it is necessary to compare ListA with a ListB of Lists to determine if ListA has the same elements of any List in ListB . In other words : If ListA is included in ListB.Both collections are queried with Linq of an EF-Code-First db . ListB has...
//In reality Lists are queried of EF var ListA = new List < Element > ( ) ; var ListB = new List < List < Element > > ( ) ; List < Element > solution ; bool flag = false ; foreach ( List e1 in ListB ) { foreach ( Element e2 in ListA ) { if ( e1.Any ( e = > e.id == e2.id ) ) flag = true ; else { flag = false ; break ; }...
How to compare list efficiently ?
C#
I am creating a simple function that creates a random file . To be thread safe , it creates the file in a retry loop and if the file exists it tries again.According to MSDN , the HResult value is derived from COM which would seem to indicate it will only work on Windows , and it specifically lists them as `` Win32 code...
while ( true ) { fileName = NewTempFileName ( prefix , suffix , directory ) ; if ( File.Exists ( fileName ) ) { continue ; } try { // Create the file , and close it immediately using ( var stream = new FileStream ( fileName , FileMode.CreateNew , FileAccess.Write , FileShare.Read ) ) { break ; } } catch ( IOException e...
Does .NET Standard normalize HResult values across every platform it supports ?
C#
A compiler that must translate a generic type or method ( in any language , not just Java ) has in principle two choices : Code specialization . The compiler generates a new representation for every instantiation of a generic type or method . For instance , the compiler would generate code for a list of integers and ad...
public class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; String [ ] newArray = t.toArray ( new String [ 4 ] ) ; } @ SuppressWarnings ( `` unchecked '' ) public < T > T [ ] toArray ( T [ ] a ) { //5 as static size for the sample ... return ( T [ ] ) Arrays.copyOf ( a , 5 , a.getClass ( )...
Useless expectation from compiler when dealing with generics ?
C#
I have a VB class which overloads the Not operator ; this does n't seem to be usable from C # applications.I can use this in VB.NET : I am trying to us this in a C # application but it wo n't build.I get the error Operator ' ! ' can not be applied to operand of type 'MyClass'Can anyone tell me what I am missing ?
Public Shared Operator Not ( item As MyClass ) As Boolean Return FalseEnd Operator If Not MyClassInstance Then ' Do somethingEnd If if ( ! MyClassInstance ) { // do something }
Using overloaded VB.NET Not operator from C #
C#
Possible Duplicate : What is the “ ? ? ” operator for ? Please explain me what is use of `` ? ? '' in below code and what is `` ? ? '' used for . { e.Description = `` The Order Date must not be in the future . `` ; return false ; } the above code is at http : //nettiers.com/EntityLayer.ashxThanks .
if ( ( this.OrderDate ? ? DateTime.MinValue ) > DateTime.Today )
What is use of `` ? ? ''
C#
I 'm writing an application using Roslyn to syntactically and semantically analyse C # source code . For each type defined in the source code being analysed , I would like to store whether it 's a reference type ( a class ) , a value type ( a struct ) or an interface.What 's the appropriate/official term for a type 's ...
class A { //This type 's type ( A 's type ) is 'class ' ( i.e . a reference type ) . }
What 's the ( official ) term for a type 's type ?
C#
http : //dotnetpad.net/ViewPaste/s6VZDImprk2_CqulFcDJ1AIf I run this program I get `` list '' sent out to the output . Why does n't this trigger an ambiguous reference error in the compiler ?
public class A { public virtual string Go ( string str ) { return str ; } } public class B : A { public override string Go ( string str ) { return base.Go ( str ) ; } public string Go ( IList < string > list ) { return `` list '' ; } } public static void Main ( string [ ] args ) { var ob = new B ( ) ; Console.WriteLine...
Why does n't this trigger an `` Ambiguous Reference Error '' ?
C#
That is , I have a method such as the following : I would like to call this method from the command line , by reading the standard array of command line arguments . The obvious way to do it would be as follows : Is it possible to do this in a more concise way ?
public static int CreateTaskGroup ( string TaskGroupName , string Market = `` en-us '' , string Project = `` MyProject '' , string Team = `` DefaultTeam '' , string SatelliteID= '' abc '' ) ; if ( args.Length == 1 ) CreateTaskGroup ( args [ 0 ] ) ; if ( args.Length == 2 ) CreateTaskGroup ( args [ 0 ] , args [ 1 ] ) ; i...
In C # , is it possible to call a method ( which has default parameters ) with `` as many parameters as I have '' ?
C#
I 'm just asking this , because the same happened to me when trying to iterate over a DataRowCollection : I saw @ Marc Gravell answer in Why is there no Intellisense with 'var ' variables in 'foreach ' statements in C # ? , and now it 's clear to me why this is happening.I decided to take a look at the code of the Data...
DataSet s ; ... foreach ( var x in s.Tables [ 0 ] .Rows ) { //IntelliSense does n't work here . It takes ' x ' as an object . } return this.list.GetEnumerator ( ) ;
Is .NET old code updated in new releases ?
C#
In C # , would there be any difference in performance when comparing the following THREE alternatives ? ONETWOTHREE
void ONE ( int x ) { if ( x == 10 ) { int y = 20 ; int z = 30 ; // do other stuff } else { // do other stuff } } void TWO ( int x ) { int y ; int z ; if ( x == 10 ) { y = 20 ; z = 30 ; // do other stuff } else { // do other stuff } } void THREE ( int x ) { int y = 20 ; int z = 30 ; if ( x == 10 ) { // do other stuff } ...
will declaring variables inside sub-blocks improve performance ?
C#
I have several bool elements and I am checking it if returns me false.I want if one of p* ( ) returns false in any case i returns false.Is it right way or two false returns true ? I want all p* ( ) return true i returns true..
bool i = false ; switch ( idcount ) { case 1 : i = p1 ( ) ; break ; case 2 : i = p1 ( ) & p2 ( ) ; break ; case 3 : i = p1 ( ) & p2 ( ) & p3 ( ) ; break ; case 4 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) ; break ; case 5 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) & p5 ( ) ; break ; case 6 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4...
Check severeal boolean returns in same time
C#
I have a helper method for my unit tests that asserts that a specific sequence of events were raised in a specific order . The code is as follows : Example usage is as follows : And the code under test : So the test expects FuelFilled to be fired before FuelChanged but in actuality FuelChanged is fired first , which fa...
public static void ExpectEventSequence ( Queue < Action < EventHandler > > subscribeActions , Action triggerAction ) { var expectedSequence = new Queue < int > ( ) ; for ( int i = 0 ; i < subscribeActions.Count ; i++ ) { expectedSequence.Enqueue ( i ) ; } ExpectEventSequence ( subscribeActions , triggerAction , expecte...
Test helper for expected events sequence reporting duplicate events
C#
I have a simple class that is defined as below.In Main methodIs garbage collector supposed to main reference for Person.p and when exactly will the destructor be called ?
public class Person { public Person ( ) { } public override string ToString ( ) { return `` I Still Exist ! `` ; } ~Person ( ) { p = this ; } public static Person p ; } public static void Main ( string [ ] args ) { var x = new Person ( ) ; x = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ...
Garbage Collector Behavior for Destructor
C#
I have a string `` THURSDAY 26th JANUARY 2011 '' .When I format this using CultureInfo.ToTitleCase ( ) : It is displayed like this : `` Thursday 26Th January 2011 '' . This is exactly what I need ... except the T in 26Th has been capitalised . Is there any way to stop this from happening as it is a date and looks wrong...
var dateString = `` THURSDAY 26th JANUARY 2011 '' ; var titleString = myCultureInfoObject.TextInfo.ToTitleCase ( dateString ) ;
C # ToTitleCase and text-formatted dates/times
C#
I am writing a c # console client to connect to SignalR service of a server . Using a bit of Wiresharking , Firebugging and examining the ... /signalr/hubs document on the server , I was able to connect on the default `` /signalr '' URL : Now I need to find outWhat hubs are there available on the server to connect to ?...
var connection = new HubConnection ( `` https : //www.website.com '' ) ; var defaultHub = connection.CreateHubProxy ( `` liveOfferHub '' ) ; connection.Start ( ) .ContinueWith ( task = > { if ( task.IsFaulted ) { Console.WriteLine ( `` Error opening the connection : '' + task.Exception.GetBaseException ( ) ) ; } else {...
How to `` get to know '' an undocumented SignalR server ?
C#
I 'm making an interval collection extension of the famous C # library C5 . The IInterval interface defines an interval with comparable endpoints ( irrelevant members removed ) : This works well in general , since interval endpoints can be anything comparable like integers , dates , or even strings.However , it is some...
public interface IInterval < T > where T : IComparable < T > { T Low { get ; } T High { get ; } }
Is there an interface in C # for interval-scaled values ?
C#
I am using EntityFramework to select data from my mssql database . My query looks something like this : This query takes about 10 seconds.This query takes less than 1 second.I just found out that EntityFramework generates two different queries.Query 1 : Query 2 : Is there a way to speed up the first one or another way ...
int param = 123456 ; using ( var context = new DatabaseContext ( ) ) { var query = context.Table.AsQueryable ( ) ; var result = query.Where ( o = > o.Id == param ) .ToList ( ) ; } using ( var context = new DatabaseContext ( ) ) { var query = context.Table.AsQueryable ( ) ; var result = query.Where ( o = > o.Id == 12345...
EntityFramework 6.1.1 with Linq Performance issue
C#
I am reading the source code of Interactive Extensions and have found a line that I can not understand : I also do not see any relevant remarks in the docs for IsFaulted or Exception properties.Why this line var ignored = t.Exception ; // do n't remove ! is needed in this context ? A related question : I thought that s...
public static Task < bool > UsingEnumerator ( this Task < bool > task , IDisposable disposable ) { task.ContinueWith ( t = > { if ( t.IsFaulted ) { var ignored = t.Exception ; // do n't remove ! } if ( t.IsFaulted || t.IsCanceled || ! t.Result ) disposable.Dispose ( ) ; } , TaskContinuationOptions.ExecuteSynchronously ...
C # Tasks - Why a noop line is needed in this case
C#
About half of the examples I see for Linq queries using the Any method do so by applying it to the results of a Where ( ) call , the other half apply it directly to the collection . Are the two styles always equivalent , or are there cases wheres that they could return different results ? My testing supports the former...
List < MyClass > stuff = GetStuff ( ) ; bool found1 = stuff.Where ( m = > m.parameter == 1 ) .Any ( ) ; bool found2 = stuff.Any ( m = > m.parameter == 1 ) ;
Are Where ( condition ) .Any ( ) and Any ( condition ) equivalent
C#
I have a rectangle body that is being fired from a canon at a 45degree Angle . The body is also rotated up at a 45 degree angle and I have set the mass to be at the front of the body . The body goes up in the air fine , however , as the body comes back down to earth it does not rotate . Is there a way so that the mass ...
Body = BodyFactory.CreateRectangle ( world , ConvertUnits.ToSimUnits ( texture.Width ) , ConvertUnits.ToSimUnits ( texture.Height ) ,100f , postition , this ) ; Body.Mass = 1 ; Body.LocalCenter = new Vector2 ( ConvertUnits.ToSimUnits ( Texture.Width ) , ConvertUnits.ToSimUnits ( Texture.Height / 2 ) ) ; Body.UserData =...
Body not rotating to face downward with gravity
C#
I 'm trying to implement a similar method as Tuple < T1 , T2 > .Create < T1 , T2 > ( T1 item1 , T2 item2 ) , but I still have to specify the type parameters whereas Tuple.Create infers them.I think the definition is right . What am I doing wrong ? Here 's my code :
public class KeyValuePair < K , V > { public K Key { get ; set ; } public V Value { get ; set ; } public static KeyValuePair < K , V > Create < K , V > ( K key , V value ) { return new KeyValuePair < K , V > { Key = key , Value = value } ; } }
How is Tuple < T1 , T2 > .Create < T1 , T2 > ( T1 item1 , T2 item2 ) implemented ?
C#
Assuming the following domain entity : I need to know if the user can perform `` Edit '' action . So i 've 2 solutions : Create a CanEdit method inside the User entityCreate a CanEdit Extension Method for User type : Both solution works , but the question is WHEN use standard methods vs using Extensions methods ?
public enum Role { User = 0 , Moderator = 1 , Administrator = 2 } public class User { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Email { get ; set ; } public Role Role { get ; set ; } } public class User { public string FirstName { get ; set ; } public string LastName {...
Standard Methods vs Extensions Methods
C#
I 'm having a bit of a problem finding out how to cancel this task in C # . I do n't exactly have a strong understanding of handling threads and I 've tried Googling for some simple code examples to help me out but I 've gotten really no where . Here 's the piece of code I 'm working on : Where `` urls '' is an array o...
var tasks = urls.Select ( url = > Task.Factory.StartNew ( state = > { using ( var client = new WebClient ( ) ) { lock ( this ) { // code to download stuff from URL } } } , url ) ) .ToArray ( ) ; try { Task.WaitAll ( tasks ) ; } catch ( Exception e ) { textBox2.AppendText ( `` Error : `` + e.ToString ( ) ) ; }
Cancelling a task which retrieves URLs asynchronously
C#
I ran across this construct in an online tutorial : I had n't seen this syntax before and was n't sure what it meant . I am not even certain that it is valid syntax at all as I ca n't get it to compile on my own .
Dictionary < string , / > dictionary = new Dictionary < string , / > ( ) ;
What does Dictionary < string , / > mean ?
C#
I have two entities : Originally , I defined the relationship between them as one-to-many in the SubscriptionErrorMap as follows : I am using the following code for saving SubscriptionError : where subscriptionError is the entity and I am not explicitly setting the primary key field.This used to work fine . But , when ...
public class Subscription { public int SubscriptionId { get ; set ; } public virtual ICollection < SubscriptionError > SubscriptionErrors { get ; set ; } } public class SubscriptionError { public int SubscriptionErrorId { get ; set ; } public int SubscriptionId { get ; set ; } public virtual Subscription Subscription {...
One to zero-or-one relationship : Can not insert explicit value for identity column in table when IDENTITY_INSERT is OFF
C#
I just read this post and it makes the case against implicit typing using when starting out with Test driven development/design.His post says that TDD can be `` slowed down '' when using implicit typing for the return type when unit testing a method . Also , he seems to want the return type specified by the test in ord...
public void Test_SomeMethod ( ) { MyClass myClass = new MyClass ( ) ; var result = myClass.MethodUnderTest ( ) ; Assert.AreEqual ( someCondition , result ) ; }
Implicit typing and TDD
C#
I 'm trying to find a ToggleButton associated in my CollectionViewGroup , my xaml structure is the following : How you can see I 've a CollectionViewGroup that filter the ObservableCollection binded Matches for Nation and League.For this I 've declared a ListView that have two GroupStyle , one that filter for Country a...
< UserControl.Resources > < CollectionViewSource Source= '' { Binding Matches } '' x : Key= '' GroupedItems '' > < CollectionViewSource.GroupDescriptions > < PropertyGroupDescription PropertyName= '' MatchNation '' / > < PropertyGroupDescription PropertyName= '' MatchLeague '' / > < /CollectionViewSource.GroupDescripti...
Not able to find ToggleButton in CollectionViewGroup
C#
I have the following listener setup in my Unity scene : And in my web view I have this log function : When I execute the following code , the only output that shows up in logcat are tests 5 and E : What is causing this and how can it be fixed ?
ui.OnMessageReceived += ( view , message ) = > { var path = message.Path ; var action = message.Args [ `` action '' ] ; if ( path == `` app '' ) { if ( action == `` log '' ) { Debug.Log ( `` [ W ] `` + message.Args [ `` text '' ] ) ; } } } ; log : function ( m ) { window.location.href = 'uniwebview : //app ? action=log...
UniWebView message throttling/collision ?
C#
The line in question is here : where v and b_y1 area double arrays ( double [ ] ) .What exactly is this line doing ? It was generated by converting MatLab to C++ to C # . I can provide the full function below if needed .
memcpy ( v [ 0 ] , b_y1 [ 0 ] , 160U * sizeof ( double ) ) ;
In code converted from C++ to C # , what should I use instead of memcpy ?
C#
Not sure I am asking this right or this even possible.I feel to explain my question it is best to ask right in the code at the relevant places so please see my comments in the snippet below.I wonder how to achieve this without building a new list of values for each I iteration . I feel this should not be necessary.The ...
for ( int i = 0 ; i < 3 ; i++ ) // 3 iterations ( X , Y ; Z ) { // what here ? how to make the data component of Vector3D a variable for ( int k = 0 ; k < = Points.Count - 1 ; k++ ) { Vector2D TL = new Vector2D ( ) ; TL.x = ( ( 1 / ( float ) FrameCount.Sum ( ) ) * k ) ; TL.y = Points [ k ] .x ; // on i = 0 want Points ...
How to make a struct component a variable ?
C#
If I am exposing a internal member via a Collection property via : When this property is called what happens ? For example what happens when the following lines of code are called : It 's clear that each time this property is called a new reference type is created but what acctually happens ? Does it simply wrap the IL...
public Collection < T > Entries { get { return new Collection < T > ( this.fieldImplimentingIList < T > ) ; } } T test = instanceOfAbove.Entries [ i ] ; instanceOfAbove [ i ] = valueOfTypeT ;
Does a Collection < T > wrap an IList < T > or enumerate over the IList < T > ?
C#
I want to highlight an object in Vim C # .I do the following in cs.vim : And highlight it in my color themeHowever it paints also the . and the first letter from the next `` word '' .How to highlight only the match before the dot ? EDIT Thanks to the @ romainl answer I found out that \zs sets the start of a match and \...
syn match csObject `` [ A-Z ] [ _a-zA-Z0-9 ] *\ . [ A-Z ] '' hi csObject guifg= # ff0000 syn match csObject `` [ \t\ ( \ ! ] \zs [ A-Z ] [ _a-zA-Z0-9 ] \ { - } \ze\ . [ A-Z ] ''
Vim - How to highlight a part of a pattern
C#
I just noticed my Excel service running much faster . I 'm not sure if there is an environmental condition going on . I did make a change to the method . Where before it wasNow its attribute is removed and the method moved into another classBut , I did this because the Method is not called or used as a service . Instea...
class WebServices { [ WebMethod ( /* ... */ ) ] public string Method ( ) { } } class NotWebService { public string Method ( ) { } } WebServices service = new WebServices ( ) ; service.Method ( ) ; NotWebService notService = new NotWebService ( ) ; notService.Method ( ) ;
C # - Can WebMethodAttribute adversely effect performance ?
C#
I have a View that displays a Part . All parts contain a list of identifiers . In my View I display Part Properties and a DataGrid with all the Identifiers of that part.Now if I change a value of an identifier , I want another value update to the default . But if I change my identifier value and set the default of the ...
< DataGrid > < DataGridTemplateColumn Header= '' Company '' > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < ComboBox x : Name= '' CompanyEditComboBox '' ItemsSource= '' { Binding RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } , Path=DataContext.Companies } '' SelectedItem= ''...
Update DataGrid cell if other cell changes
C#
The following C # snippet compiles and runs under my Visual Studio 2010 : Note the trailing comma in the object initializer.Is this legal C # and does it have any useful purpose , or I have just hit a ( benign ) compiler bug ?
struct Foo { public int A ; } // ..var foo = new Foo { A = 1 , } ;
new Foo { A = 1 , } Bug or Feature ?
C#
I am trying to dynamically re-structure some data to be shown in a treeview which will allows the user to select up to three of the following dimensions to group the data by : So for example , if the user were to select that they wanted to group by Company then Site then Division ... the following code would perform th...
OrganisationCompanySiteDivisionDepartment var entities = orgEntities// Grouping Level 1.GroupBy ( o = > new { o.CompanyID , o.CompanyName } ) .Select ( grp1 = > new TreeViewItem { CompanyID = grp1.Key.CompanyID , DisplayName = grp1.Key.CompanyName , ItemTypeEnum = TreeViewItemType.Company , SubItems = grp1 // Grouping ...
Create GroupBy Statements Dynamically
C#
I do n't understand why the following code produces an error . Normally I can figure things out from the language specification , but in this case I do n't understand the language specification.This is n't causing problems in my code , by the way , I just want to understand the language.Example : This behavior appears ...
bool success ; try { success = true ; } catch { success = false ; } finally { Console.WriteLine ( success ) ; // ERROR : Local variable 'success ' might not be initialized before accessing } static void F ( ) { int i , j ; try { goto LABEL ; // neither i nor j definitely assigned i = 1 ; // i definitely assigned } catc...
In C # , why is a variable not definitely assigned at the beginning of a finally block ?
C#
I 'm trying to investigate whether dictionaries with enum keys still generate garbage in newer versions of .Net ( say > = 4 ) See Shawn Hargreaves blog post here for details on why I 'm even fretting about this ... ( http : //blogs.msdn.com/b/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx ) Ve...
.method private hidebysig instance int32 FindEntry ( ! TKey key ) cil managed { // Method begins at RVA 0x61030 // Code size 138 ( 0x8a ) .maxstack 3 .locals init ( [ 0 ] int32 , [ 1 ] int32 ) IL_0000 : ldarg.1 IL_0001 : box ! TKey < -- -- Hmmmm ! IL_0006 : brtrue.s IL_000e IL_0008 : ldc.i4.5 IL_0009 : call void System...
.Net Framework 4.0 - Opcodes.Box present in Dictionary with int key
C#
In a previous question one of the comments from Dr. Herbie on the accepted answer was that my method was performing two responsibilities..that of changing data and saving data.What I 'm trying to figure out is the best way to separate these concerns in my situation.Carrying on with my example of having a Policy object ...
Policy policy = new Policy ( ) ; policy.Status = Active ; policyManager.Inactivate ( policy ) ; //method in PolicyManager which has data access and update responsibilitypublic void Inactivate ( Policy policy ) { policy.Status = Inactive ; Update ( policy ) ; } Policy policy = new Policy ( ) ; policy.Status = Active ; p...
What 's the best way to separate concerns for this code ?
C#
I have view model with 2 properties : A and B and I want to validate that A < B.Below is my simplified implementation where I use custom validation rule . Since each property is validated independently , it lead to an anoying issue : if entered A value is invalid , than it stay so even after changing B , since validati...
public class ViewModel : INotifyPropertyChanged { int _a ; public int A { get = > _a ; set { _a = value ; OnPropertyChanged ( ) ; } } int _b ; public int B { get = > _b ; set { _b = value ; OnPropertyChanged ( ) ; } } public event PropertyChangedEventHandler PropertyChanged ; public virtual void OnPropertyChanged ( [ C...
How to validate two properties which depend on each other ?
C#
Today I found something that I do n't quite understand . I got the following code in LinqPad ( version 5 ) : It appears that second loop takes twice as long as the first one . Why would this simple cast cause such an effect ? I 'm sure that there 's something simple happening under the hood that I am somehow missing .
void Main ( ) { const int size = 5000000 ; List < Thing > things = Enumerable.Range ( 1 , 5000000 ) .Select ( x = > new Thing { Id = x } ) .ToList ( ) ; var sw1 = Stopwatch.StartNew ( ) ; foreach ( var t in things ) if ( t.Id == size ) break ; sw1.ElapsedMilliseconds.Dump ( ) ; var sw2 = Stopwatch.StartNew ( ) ; IEnume...
Foreach on collection cast to IEnumerable work slower than without cast ?
C#
I 'm trying to tackle the classic handwritten digit recognition problem with a feed forward neural network and backpropagation , using the MNIST dataset . I 'm using Michael Nielsen 's book to learn the essentials and 3Blue1Brown 's youtube video for the backpropagation algorithm.I finished writing it some time ago and...
/// < summary > /// Returns the partial derivative of the cost function on one sample with respect to every weight in the network./// < /summary > public List < double [ , ] > Backpropagate ( ITrainingSample sample ) { // Forwards pass var ( weightedInputs , activations ) = GetWeightedInputsAndActivations ( sample.Inpu...
Backpropagation algorithm giving bad results
C#
I am looking at the Roslyn ObjectPool implementation ( https : //github.com/dotnet/roslyn/blob/master/src/Compilers/Core/SharedCollections/ObjectPool % 601.cs ) and I do n't get why they did not simply choose to have an array of T but instead wrap T inside a struct ? What is the purpose of this ?
[ DebuggerDisplay ( `` { Value , nq } '' ) ] private struct Element { internal T Value ; } ... private readonly Element [ ] _items ;
Roslyn ObjectPool struct wrapper