lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I am designing a HangMan game to learn how to use C # with DevExpress.My problem is that I am drawing the post with size relative to the panel size I am drawing it into , so that its size is recalculated if the window is resized . My code looks like this : This works perfectly for me , and the post drawing is resized .... | namespace HangMan { public partial class HangMan : Form { public HangMan ( ) { InitializeComponent ( ) ; this.Paint += new System.Windows.Forms.PaintEventHandler ( HangMan_Paint ) ; } void drawHangPost ( ) { //Use panel size percentages to draw the post double dWidth = pnlHang.Width ; double dHeight = pnlHang.Height ; ... | Image is duplicated when the window is maximized |
C# | I stumbled upon this weird thing today : http : //www.yoda.arachsys.com/csharp/teasers.htmlQuestion # 5 . The code : Now according to the answers on http : //www.yoda.arachsys.com/csharp/teasers-answers.html for question # 5 ... It 's a known bug due to some optimisation being done too early , collecting constants of 0... | using System ; class Test { enum Foo { Bar , Baz } ; const int One = 1 ; const int Une = 1 ; static void Main ( ) { Foo f = One - Une ; Console.WriteLine ( f ) ; } } | Why should n't this compile ? |
C# | I am using ZXing.Net library to encode and decode my video file using RS Encoder . It works well by adding and and removing parity after encoding and decoding respectively . But When writing decoded file back it is adding `` ? '' characters in file on different locations which was not part of original file . I am not g... | using ZXing.Common.ReedSolomon ; namespace zxingtest { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; string inputFileName = @ '' D : \JM\bin\baseline_30.264 '' ; string outputFileName = @ '' D : \JM\bin\baseline_encoded.264 '' ; string Content = File.ReadAllText ( inputFileName , ASCI... | Unusual Character addition after writing back decoded file |
C# | Is there a way to do this in C # ? I do n't want to have to say sc.Value every time i need to access the value . | public class SampleClass { public int value ; public SampleClass ( int v ) { value = v ; } } // i want to access value like thisSampleClass sc = new SampleClass ( 5 ) ; int i = sc ; | How do you make this parameter access syntax possible ? |
C# | I have this code written by another programmer and I cant get my head around itFrom my understanding the AppBase class of type T implements the interface IApp where T implements ? ? ? Can some one explain the last part ? | public abstract class AppBase < T > : IApp where T : AppBase < T > , new ( ) { // } | Whats happening in this Self referencing inheritance code ? |
C# | Is it possible to test for the existence of an attribute within the code of another attribute ? Say you have the following class definition : ... is it possible for MyTestAttribute.IsValid to determine whether Inception.Levels has the RequiredAttribute ? | public class Inception { [ Required ] [ MyTest ] public int Levels { get ; set ; } } public class MyTestAttribute : ValidationAttribute { public override bool IsValid ( object o ) { // return whether the property on which this attribute // is applied also has the RequiredAttribute } } | Test for Attributes From Within the Code of Other Attributes |
C# | As you can see at this link , it was possible to separate the rooting and the implementation of the old nancy1.X modules . Now that the way of defining these routes have changed , I would like to know how to code the same separation logic.For clarity , the old way to define a Get route was : Get [ `` / { category } '' ... | Get [ `` /favoriteNumber/ { value : int } '' ] = FavoriteNumber ; private dynamic FavoriteNumber ( dynamic parameters ) { return `` So your favorite number is `` + parameters.value + `` ? `` ; } | How to separate interface from implementation in nancy2.0 ? |
C# | I have a webapi that returns an object that contains some collections of objects which also contains a collection of objects . Each of these objects has a bool that represents if the object is 'published ' See classes below for general idea.What is the best way to make it so when I serialize any of these objects that a... | public class A { public int ID { get ; set ; } public List < B > b { get ; set ; } } public class B { public List < C > c { get ; set ; } public List < D > d { get ; set ; } public bool published { get ; set ; } } public class C { public string Title { get ; set ; } public bool published { get ; set ; } } public class ... | Limit objects in a collection from being serialized based on User |
C# | I want to create a class that have a class but this second class may be different each time the first class is called . For example : How can I do it to call the ServerResponseObject with different objects each time , once with TVChannelObject and once with ChannelCategoryObject ? | public class ServerResponseObject { public string statusCode { get ; set ; } public string errorCode { get ; set ; } public string errorDescription { get ; set ; } public Object obj { get ; set ; } public ServerResponseObject ( Object obje ) { obj = obje ; } } public class TVChannelObject { public string number { get ;... | How to specify a class that may contain another class |
C# | I find myself repeating calculations within a linq statements and I was wondering whether I can access already computed elements somehow . This is what I m doing : Which works fine.This is what I would like to be doing : where the price is the price I computed just after rundate . Can I access this somehow ? | var result = testdata.GroupBy ( a = > new { a.reportinggroup , a.commodity , a.timestep.Year } ) .Select ( g = > new EndResult { rundate = rundate.ToShortDateString ( ) , price = g.Sum ( a = > ( a.timestep.ispeak ( ) ) ? a.price : 0 ) / g.Sum ( a = > ( a.timestep.ispeak ( ) ) ? 1 : 0 ) , valueposition = g.Sum ( a = > (... | Using already computed element |
C# | I 've looked at the other questions around this and I just ca n't work out how to apply the answers to my particular situation . Say you have a couple of models that look like this : I want to be able to write a couple of different generic methods : one that gets the models using a provided Lambda that might look somet... | public class Person { public int PersonId { get ; set ; } } public class Business { public int BusinessId { get ; set ; } } GetWhere ( p = > p.PersonId == 1 ) GetByUniqueKey ( p = > p.PersonId , 1 ) GetByUniqueKey ( b = > b.BusinessId , 1 ) public IEnumerable < TModel > GetWhere ( Expression < Func < TModel , bool > > ... | Using the logic from one lambda within a second lambda |
C# | I have this code : I do also handle UnobservedTaskException ( by logging it ) . The problem that I face is that after task1 fails and first await results in exception , task2 completes in an error and then I have a log entry that I do not want to see as I will already log the first exception and at that point all subse... | var task1 = operation1 ( ) ; var task2 = operation2 ( ) ; var result1 = await task1 ; var result2 = await task2 ; | How to observe tasks that are not awaited due to failure in another awaited task in C # ? |
C# | i am developing application using C # ( 5.0 ) .Net ( 4.5 ) .I want to know whats the difference between below to declaration of dictionary variable.1.and 2.in 2nd declaration i have used ( ) after Dictionary < string , object > . both syntax works fine but just eager to know about internal work . | var emailtemplateValues = new Dictionary < string , object > { { `` CreatorName '' , creatorUserInfo.UserName } , { `` ProjectName '' , masterProjectInfo.Title } , { `` Reason '' , reason } } ; var emailtemplateValues = new Dictionary < string , object > ( ) { { `` CreatorName '' , creatorUserInfo.UserName } , { `` Pro... | Difference between define dictionary |
C# | I currently work on a .net core api project with VSCode , and I want to integrate ASP.NET Core Authentication and Authorization with a cookie . I tried to add services.AddAuthentication ( ) ; and services.AddAuthorization ( ) ; in Startup.cs . I 've also add the [ Authorize ] attribute in my UsersController.cs.The prob... | [ Authorize ] [ Route ( `` api/Users '' ) ] [ ApiController ] public class UsersController : ControllerBase `` iisSettings '' : { `` windowsAuthentication '' : false , `` anonymousAuthentication '' : false , `` iisExpress '' : { `` applicationUrl '' : `` http : //localhost:49086 '' , `` sslPort '' : 44343 } | Setup ASP.Net Core Authorize and Authentication Properly in a .Net Core 3.0 project |
C# | string in C # is a reference type that behave like value type . Usually programmers do not have to worry about this since strings are immutable and the language design prevents us from doing unintentional dangerous things with them . However , with the use of unsafe pointer logic is it possible to directly manipulate t... | class Program { static string foo = `` FOO '' ; static string bar = `` FOO '' ; const string constFoo = `` FOO '' ; static unsafe void Main ( string [ ] args ) { fixed ( char* p = foo ) { for ( int i = 0 ; i < foo.Length ; i++ ) p [ i ] = 'M ' ; } Console.WriteLine ( $ '' foo = { foo } '' ) ; //MMM Console.WriteLine ( ... | Unsafe string manipulation mutates unexisting value |
C# | So , this one is pretty straight forward I think.Here is my code : What is happening is that in the end the dictionary will have all the correct keys , but all of the values will be set to the fileTypes list created during the final iteration of the loop . I am sure this has something to do with the object being used a... | Dictionary < int , IEnumerable < SelectListItem > > fileTypeListDict = new Dictionary < int , IEnumerable < SelectListItem > > ( ) ; foreach ( PresentationFile pf in speakerAssignment.FKPresentation.PresentationFiles ) { IEnumerable < SelectListItem > fileTypes = Enum.GetValues ( typeof ( PresentationFileType ) ) .Cast... | Altering object is affecting previous versions of object in a foreach loop |
C# | My site calls a service ( let 's call it FooService ) that requires a very complex set of authentication protocols . The protocols are all wrapped up in a custom ClientCredentials behavior that is declared like this in code : We then register the behavior extension : Configure an endpointBehavior to use it : And set up... | class FooServiceCredentialsBehavior : ClientCredentials { public FooServiceCredentialsBehavior ( ) { //Set up service certificate var cert = CertStore.FindBySerialNumber ( certSerialNumber ) ; base.ServiceCertificate.DefaultCertificate = cert ; } } < behaviorExtensions > < add name= '' FooServiceCredentials '' type= ''... | Can you change a BehaviorExtension with WCF configuration ? |
C# | I 've read numerous articles related to proper equality in C # : http : //www.loganfranken.com/blog/687/overriding-equals-in-c-part-1/What is the best algorithm for an overridden System.Object.GetHashCode ? Assume the following sample class : Would it still be the case to compare the Values property using .Equals ( ) ?... | public class CustomData { public string Name { get ; set ; } public IList < double > Values = new List < double > ( ) ; } # region Equality public override bool Equals ( object value ) { if ( Object.ReferenceEquals ( null , value ) ) return false ; // Is null ? if ( Object.ReferenceEquals ( this , value ) ) return true... | C # equality with list-based properties |
C# | While trying to find the best approach to implementing a catch-all for any uncaught exceptions I found this.But , while implementing it , I remembered where I read : WARNING Do n't modify the Response object after calling next ( ) ... , as the response may have already started sending and you could cause invalid data t... | public async Task Invoke ( HttpContext context ) { try { await _next ( context ) ; } // A catch-all for uncaught exceptions ... catch ( Exception exception ) { var response = context.Response ; response.ContentType = `` application/json '' ; response.StatusCode = ( int ) HttpStatusCode.InternalServerError ; await respo... | Are exceptions an exception to the rule about not modifying the Response after next ( ) ? |
C# | Say I 'm using an external package for storing graphs . A BidirectionalGraph takes two templates : a vertex and an edge type : Unfortunately , this graph package does n't allow you to get the edges radiating into a vertex in a single line . Instead , you have to provide an IEnumerable , which it will populate with the ... | var graph = new BidirectionalGraph < Vertex , Edge < Vertex > > ( ) ; public static class GraphExtensions { public static IEnumerable < TEdge > IncomingEdges < TGraphSubtype , TVertex , TEdge > ( this TGraphSubtype graph , TVertex n ) where TGraphSubtype : BidirectionalGraph < TVertex , TEdge > where TEdge : IEdge < TV... | Allow templates to be inferred |
C# | We often use event handler in C # , just as below : Does this happen at compile time or run time ? What if the some_event is static member ? AFAIK , the some_event contains nothing but the entry address of some_event_handler , and the method address of some_event_handler could be determined at compile time . If some_ev... | some_event+=some_event_handler ; | When does event handler registeration happen ? |
C# | Given the following code ( which I know wo n't compile and is n't correct ) : And this example setup : How can I structure my code so that this will work ? TLDR ; I 've thought about this a little more . A different way to state my question is : how do I run the Fetch method on all the items in the myFetchers list and ... | public abstract class Fetcher { public abstract IEnumerable < object > Fetch ( ) ; } public class Fetcher < T > : Fetcher { private readonly Func < IEnumerable < T > > _fetcher ; public Fetcher ( Func < IEnumerable < T > > fetcher ) { _fetcher = fetcher ; } public IEnumerable < T > Fetch ( ) = > _fetcher ( ) ; // overr... | Allow derived type cast as parent type to return ` object ` , but using the derived type 's method |
C# | So I have created a provider ( a few of them actually ) and I am realising there is a bit of a pattern in some of my logic . It is being repeated and I reckon I can remove lots of lines of code if I can just create this extension method : DSo , basically what is happening is something like this : Now , I do this in a l... | // Get our item to be deletedvar model = await this._service.GetAsync ( id ) ; // If we have nothing , throw an errorif ( model == null ) throw new HttpException ( 404 , string.Format ( Resources.GenericNotFound , `` List item '' ) ) ; // Get our item to be deletedvar model = await this._service.GetAsync ( id ) .ThowIf... | Static Method for handling null returns |
C# | This is a bit of a weird one.I 'm building a web application and I was putting together a simple factory-pattern-like thing to handle some object instantiation . I do n't like big ugly switch-case blocks , so I tend to do this : and then the switch block becomes MyBaseClass selectedThing = OptionMapping [ currentOption... | public enum Option { Option1 , Option2 , Option3 } public Dictionary < Option , Func < MyBaseClass > > OptionMapping = new Dictionary < Option , Func < MyBaseClass > > { { Option1 , ( ) = > new DerivedClassOne ( ) } , { Option2 , ( ) = > new DerivedClassTwo ( ) } , { Option3 , ( ) = > new DerivedClassThree ( ) } } ; pu... | Dictionary < X , Func < Y > > accessing the containing Dictionary from a Func < > within it |
C# | I have researched into this extensively , but can not seem to find anything in its regard.If I was to use an if statement as a validation and needed to write something along these lines : Could I write the above as the following with the same result : I can not see the result of this and am wondering if in this case it... | if ( split [ lengthsplit + 1 ] == `` = '' & & split [ lengthsplit - 1 ] == `` = '' ) if ( split [ lengthsplit +- 1 ] == `` = '' ) | What would +- do as an operator in c # |
C# | I am looking for a way to inherit generics with inherited parameterizations - or if that 's not possible , the closest way to get the same functionality.Consider the following : Class B inherits from class AClass D inherits from Class CNow , I have one class : with constructor : Now , I wish to extend class A as so : C... | abstract class A < T > where T : C public A ( T t ) class B < D > : A < C > public B ( D t ) : base ( t ) { /*stuff here*/ } | Inheriting generics with inherited parameterizations |
C# | The short version : What is the best way of overloading two methods , when one accepts an Expression < Action > , and another accepts an Expression < Action < T > > ? The longer version : Let 's say I have the following methods in a ( badly designed ) class : Now , it may be me being particularly dim , but I would expe... | void Main ( ) { Foo ( t = > Bar ( t ) ) ; } void Foo ( Expression < Action > action ) { `` Method 1 ! `` .Dump ( ) ; } void Foo < T > ( Expression < Action < T > > action ) { `` Method 2 ! `` .Dump ( ) ; } void Bar ( String thing ) { // Some bar-like thing } Foo < String > ( t = > Bar ( t ) ) ; | Overload precedence between Expression < Action > and Expression < Action < T > > |
C# | This code gives an error : But if I separate the classes , there is no error : | public class A < T > { public class B < T1 > : A < T1 > { public static implicit operator bool ( B < T1 > b ) = > true ; } } public class A < T > { } public class B < T > : A < T > { public static implicit operator bool ( B < T > b ) = > true ; } | Why does an implicit operator method in a nested class not compile ? |
C# | I 'm having some troubles when saving in the database a model with a little complex relationship.The UML of the classes is : The classes definition are : I 'm able to run a migration and looking into the database the tables and columns created by the framework seems fine to me . But , when saving an exception happens .... | public abstract class EntityBase { public virtual Guid Id { get ; set ; } } public class LoanRequest : EntityBase { [ Key , DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public Guid Id { get ; set ; } public virtual Applicant Applicant1 { get ; set ; } public virtual Applicant Applicant2 { get ; set ; } } pu... | EF relation one-to-two |
C# | In my app , I have a method that gets invoked every time an update happens on some queue on a server . The app is initialized to behave this way.Now , each time the method is invoked with the latest data , I want to treat it like a part of a stream of event and hence make this a part of an Observable that never ends wi... | //This method is invoked every time an update happens on the serverpublic virtual void MessageHandler ( MyObject1 object1 , MyObject2 object2 ) { Observable.Create < MyObject3 > ( observer = > { var object3 = new MyObject3 ( object1 , object2 ) ; observer.OnNext ( object3 ) ; return Disposable.Empty ; } ) .Subscribe ( ... | Create an observable on a method |
C# | I want to match the following strings : Can I achieve this using only one regular expression ? I am currently using this one '^\ [ ( { ) ? .+ ( } ) ? ] $ ' , but it will match also : I need to to match } only if { is used.Please , note I can use only regular expression match function as I have implemented it as SQL CLR... | [ anything can be here ] [ { anything can be here } ] [ anything can be here } ] [ { anything can be here ] | Regular Expression - Match End if Start is Match |
C# | Consider the following scenariowhere multiple threads access this variable via a method callingwhere this method does some heavy weight operations to retrieve the dataMy problem here is that if I useGetorAdd the HeavyDataLoadMethodgets executed even if it is not needed.I was wondering if there is some way to take advan... | private static ConcurrentDictionary < string , ConcurrentDictionary < string , string > > CachedData ; ConcurrentDictionary < string , string > dic = CachedData.GetorAdd ( key , HeavyDataLoadMethod ( ) ) private ConcurrentDictionary < string , string > HeavyDataLoadMethod ( ) { var data = new ConcurrentDictionary < str... | .NET Force method deferred execution |
C# | How do I refactor this code so I can centralize the projection ? Basically , I have lots of case statements and a long projection on each case statement . I 'm worried that once the DTO needs to change , say add a new field , the other cases ' projection might not be consistent with each other ( forgot or missed updati... | public IEnumerable < ItemDto > GetItemsByType ( int itemId , ItemType itemType ) { IEnumerable < ItemDto > items = null ; try { var tempItems= _Items.Get ( i = > i.ItemId == itemId & & o.Active == true ) ; switch ( itemType ) { case ItemType.Normal : items = from item in tempItems select new ItemDto { // many fields he... | Centralizing or consolidating LINQ select |
C# | Say I have the following method : And then I use this method in a LINQ query like so : This fails with : Error 1 The type arguments for method 'System.Linq.Enumerable.Select ( System.Collections.Generic.IEnumerable , System.Func ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.Of co... | static int MethodWithDefaultParameters ( int a , int b=0 , int c=1 ) { return a + b + c ; } Enumerable.Range ( 1,10 ) .Select ( MethodWithDefaultParameters ) ; Enumerable.Range ( 1,10 ) .Select ( i = > MethodWithDefaultParameters ( i ) ) ; | C # Type Inference fails with methods that contain default parameters |
C# | I 'm just messing around with some data types of C # in order to understand them.I 've been trying for a while to understand why this dictionary is turned into a KeyValuePair.Here 's my code : And I 'm getting this error : Error CS0030 Can not convert type 'System.Collections.Generic.KeyValuePair < string , int > ' to ... | class Program { static Dictionary < string , int > operatii ( int a , int b ) { Dictionary < string , int > calculare = new Dictionary < string , int > ( ) ; calculare.Add ( `` suma '' , a + b ) ; calculare.Add ( `` produs '' , a * b ) ; return calculare ; } static void Main ( string [ ] args ) { foreach ( Dictionary <... | Why is Dictionary transformed into a KeyValuePair here ? |
C# | Hey its a simple script whit animation params , but I do n't know why my if with getkeydown is not executing ! Its suppose to play an idle animation if key is not being pressed but thats not happening instead its just not going trough that part of the code . | public class PlayerMovement : MonoBehaviour { private Rigidbody2D rigidbodyMurrilo ; public float speed ; public Animator anim ; public bool FacingRigth ; public Transform transform ; private void Start ( ) { rigidbodyMurrilo = GetComponent < Rigidbody2D > ( ) ; anim = GetComponent < Animator > ( ) ; FacingRigth = true... | My getkeydown is not being recognized |
C# | I got into some trouble with EntityFramework and the following datamodel ( see simplified diagram ) .The Matter object can be thinked as the `` main container '' . There are Bill and BillRecord . There is a one-to-many association from Bill to BillRecord . Precisely , a Bill can reference many BillRecord ( possibly 0 )... | System.Data.SqlServerCe.SqlCeException : The primary key value can not be deleted because references to this key still exist . [ Foreign key constraint name = FK_dbo.BillRecordDboes_dbo.BillDboes_BillId ] protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < MatterDbo > ( ) .Ha... | EntityFramework : CascadeOnDelete only if parent object is deleted |
C# | I have a method that manipulates a value tuple with multiple fields . That tuple is returned from another method and deconstructed , in order to simplify further usages of its fields : However , now I need to pass the entire tuple down to another method that expects it : Is there an easy or clean way to `` reconstruct ... | var ( a , b , c ) = GetValueTuple ( ) ; private void ExpectsTuple ( ( a , b , c ) tuple ) { ... } this.ExpectsTuple ( /* need to pass tuple here */ ) ; var ( a , b , c ) tuple = GetValueTuple ( ) ; | How to reference a deconstructed value tuple without making a copy of it |
C# | In a console app , from a static method in main class Program , I am calling : I have both set a break-point , and also checked the expected outcome ( module installed locally ) , but from all indications the method 'EnsureModuleLocalInstall ' is not being executed.Am I missing something obvious , or am I expecting too... | internal class Module { public bool EnsureModuleLocalInstall ( ) { if ( CheckModuleUpToDateLocal ( ) ) return true ; else if ( DownloadComponentData ( ) ) if ( InstallModuleLocal ( ) ) return true ; return false ; } } var availableModules = new List < Module > ( ) ; ... // Add several 'Modules ' to listvar installed = ... | Why wo n't a method execute from within LINQ Where method |
C# | I 've got the following typo : used in the following : I intended it to be += , but I 'm left wondering what `` = +var '' means.. | subcomponentGroupCount = +subcomponentCount ; int subcomponentGroupCount = 0 ; foreach ( Subcomponent subcomponent in group.Subcomponents ) { int subcomponentCount = task.TaskDevice.TaskDeviceSubcomponents.Count ( tds = > tds.TemplateID == subcomponent.TemplateID ) ; subcomponentGroupCount = +subcomponentCount ; } | What does =+ mean and why does it compile ? |
C# | How do I retrieve values from @ for loop into jquery..Each value inside for loop should have different id , and jquery should get each separate id ... .My for loop , My jquery which is n't helping , Thanks in advance ... | @ for ( int i = 0 ; i < searchList.Count ; i++ ) { < label for= '' input @ i '' > < input type= '' checkbox '' id= '' input @ i '' / > @ searchList [ i ] < /label > } $ ( `` # input @ i '' ) .on ( `` click '' , function ( ) { var currentChk = $ ( this ) ; var propCheck = currentChk.prop ( `` checked '' ) ; if ( propChe... | Retrieving values from for loop into jquery |
C# | I tried to reference System.Device in a Razor view of my MVC C # project . It complained that the reference was missing even after I added it to the project . I did not have the assembly in my GAC , and to test I added the below dummy line in my global.asax.cs file ( and compiled with multiple debug flags enabled , I w... | new System.Device.Location.GeoCoordinate ( ) ; System.Diagnostics.Debug.WriteLine ( System.Device.Location.GeoCoordinate.Unknown.IsUnknown ) ; | How to determine if Copy Local is necessary |
C# | I have a console based MEF application the host ( CompositionContainer ) of which loads available plugin assemblies based on the command line parameter , for example : will load the host ( app.exe ) and plugin1 . The VS solution is structured such that each plugin has it 's own project ( hence it 's own assembly ) .The... | app.exe plugin1 | Utilising methods available in plugin1 in plugin2 via MEF |
C# | Given the following example class : If I am reflecting against method Foo < > .Bar < > ( ... ) , and examining the parameter types , say : both argType1 and argType2 look similar : FullName property is nullName property is `` T '' or `` S '' respectivelyIsGenericParameter is trueIs there anything in the parameter type ... | class Foo < T > { void Bar < S > ( T inputT , S inputS ) { // Some really magical stuff here ! } } var argType1 = typeof ( Foo < > ) .GetMethod ( `` Bar '' ) .GetParameters ( ) [ 0 ] .ParameterType ; var argType2 = typeof ( Foo < > ) .GetMethod ( `` Bar '' ) .GetParameters ( ) [ 1 ] .ParameterType ; | Distinguish between a class generic type parameter and method generic type parameter |
C# | I do n't understand what the difference between these 2 variations are . What is the pros/cons of each approach ? | 1. a.MyEvent += new MyClass.MyEventDelegate ( FireEvent ) ; 2. a.MyEvent += FireEvent ; | Should I new-up a new delegate or just add the method to an event ? |
C# | I have a library of html helpers as a separate project . Right now it references system.web.mvc of version 4.If I try to use this library in a project that uses mvc3 it throws an error when a helper is attempted to be used : I understand that I need to build my helpers project with system.web.mvc of version 3 reference... | Compiler Error Message : CS1705 : Assembly 'MyHtmlHelpers , Version=3.7.4.0 , Culture=neutral , PublicKeyToken=null ' uses 'System.Web.Mvc , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 ' which has a higher version than referenced assembly 'System.Web.Mvc , Version=3.0.0.0 , Culture=neutral , Pub... | How to set up project of htmlHelpers so that it produces two dlls - for mvc3 and mvc4 ? |
C# | I want to create a game where you try to avoid objects ( circles ) that are `` attacking '' you . The way I did this : First calculate the x_and y difference between the object and me ( in this code AI_x is the object 's x-location ( AI_y : y-location ) and x , y the player 's location ) Calculate the angle the object ... | namespace AI { public partial class mainClass : Form { //variables int health ; double startPosition_x , startPosition_y , angle ; float x , y , speed , AI_x , AI_y , distanceToPlayer_x , distanceToPlayer_y ; //gameloop Timer gameLoop ; //field Bitmap bmp ; //player color Pen playerColor ; //Random Random random_x , ra... | Attack/Follow my player |
C# | I have textual table : where I would like to match all numbers , except those in first column.I 've tried to use negative lookbehind without success : How to match all numbers except those in first column ( 13.5 , 14 , 14.5 , 15 , 15.5 ) ? | 13.5 0.12557 0.04243 -0.0073 0.00377 14 0.12573 0.05 -0.00697 0.00437 14.5 0.12623 0.05823 -0.00703 0.005 15 0.12853 0.0686 -0.00627 0.00493 15.5 0.1299 0.08073 -0.00533 0.0063 ( ? < ! ^ ) [ \d.E- ] + | How to skip a column ? |
C# | If I have a generic method like this one : I could call it by specifying an interface type , for example ICollection < int > Now assume I have a struct that implements ICollection < int > : I ca n't specify it explicitly as the type argument , but if I have a variable of type ICollection < int > that has the underlying... | static void Foo < T > ( ) where T : class { } Foo < ICollection < int > > ( ) ; struct Bar : ICollection < int > static void Foo < T > ( T arg ) where T : class { } ICollection < int > bar = new Bar ( ) ; Foo < ICollection < int > > ( bar ) ; | Why specifying a generic argument as interface is not an error with a class constraint ? |
C# | I have the following method which is used to retrieve all values as strings from an object using reflection . The object can have IEnumerables within them and I also want to retrieve these values . A list of ignore fields also needs to be taken into account so that those field 's values are not returned.This method doe... | public static IEnumerable < string > StringContent ( this object obj , IEnumerable < string > ignoreProperties = null ) { Type t = obj.GetType ( ) ; foreach ( var prop in t.GetProperties ( ) ) { if ( ignoreProperties ! = null & & ignoreProperties.Contains ( field.Name ) ) { continue ; } var value = prop.GetValue ( obj ... | Strip all values from C # objects using Reflection |
C# | If not and the set of reference types and value types are mutually exclusive , why does n't this compile : The compiler states : `` Type already defines a member called 'Do ' with the same parameter types . `` , but T and T are not the same here . One is constrained to structs , the other is constraint to classes . A c... | public static void Do < T > ( T obj ) where T : struct { } public static void Do < T > ( T obj ) where T : class { } | Can a type be a reference type and a value type at the same time ? |
C# | I 'm new to Windows 8.1 development , so forgive me if this question is obvious or rudimentary . I 've experimented around with the various attributes quite a bit , and I ca n't make it work the way I want it to , so I figured maybe someone here could give me a hand.A description of what I 'm doing : I made a UserContr... | < UserControl x : Name= '' UserControlRoot '' d : DesignHeight= '' 300 '' d : DesignWidth= '' 400 '' mc : Ignorable= '' d '' > < Grid x : Name= '' LayoutRoot '' Margin= '' 0 '' Background= '' Red '' > < Grid.Resources > < Style TargetType= '' TextBlock '' x : Key= '' UCTextBlock '' > < Setter Property= '' FontSize '' V... | How do I make my TextBlocks be the correct sizes in my C # XAML Windows 8.1 app ? |
C# | I have the following scenario : I 'm trying to lock a thread in place , if that threads 'custom ' id matches the one that has already entered the locked section off code , but not if the id differs.I created some sample code to explain the behaviour I want Now this works 100 % for what I extended , where id example 1 d... | class A { private static Dictionary < int , object > _idLocks = new Dictionary < int , object > ( ) ; private static readonly object _DictionaryLock = new object ( ) ; private int _id ; private void A ( int id ) { _id = id ; } private object getObject ( ) { lock ( _DictionaryLock ) { if ( ! _idLocks.ContainsKey ( _id )... | Improved Thread locking advice needed |
C# | I 'm experimenting with custom integer types and came across an interesting issue involving generics , implicit conversions , and 32 bit integers.Below is a stripped down example of how to reproduce the problem . If I have two implicit methods that convert int to MyInt and vice versa , I get a compilation error which l... | using Xunit ; public class MyInt { public int Value ; //If I remove either one of the implicit methods below , it all works fine . public static implicit operator int ( MyInt myInt ) { return myInt.Value ; } public static implicit operator MyInt ( int i ) { return new MyInt ( ) { Value = i } ; } public override bool Eq... | 32 bit implicit conversions fail generic overload resolution |
C# | I have a folder fuill of images and have the image name and the full file path stored in an array in my program . Is it possible to get just the folder and the filename from the filepath.So If I have a filepath ofI need to get | C : \Users\Ryan\Documents\myImage.jpg Documents\myImage.jpg | Get the folder of a file . |
C# | Why does the following crash with a NullReferenceException on the statement a.b.c = LazyInitBAndReturnValue ( a ) ; ? Assignment expressions are evaluated from right to left , so by the time we are assigning to a.b.c , a.b should not be null . Oddly enough , when the debugger breaks on the exception , it too shows a.b ... | class A { public B b ; } class B { public int c ; public int other , various , fields ; } class Program { private static int LazyInitBAndReturnValue ( A a ) { if ( a.b == null ) a.b = new B ( ) ; return 42 ; } static void Main ( string [ ] args ) { A a = new A ( ) ; a.b.c = LazyInitBAndReturnValue ( a ) ; a.b.other = L... | Member references and assignment order of evaluation |
C# | My object like like thisI have a list of this objects in this class Where data is like thisI want to filter this list so that I can get an output like this ( all the possible combination of city and region regardless of postcode ) .I have wrote some query like thisBut this is giving me a result of first item only like ... | public class Region { public Region ( ) ; public string City { get ; set ; } public int PostCode { get ; set ; } public string WfRegion { get ; set ; } } Rodney , 7845 , AucklandRodney , 3435 , AucklandRodney , 4566 , AucklandRodney , 3445 , North Island Rodney , 7845 , Auckland Rodney , 3445 , North Island var cities ... | Get distinct items by combination from list C # |
C# | I have two simple classes.I build and instantiate class C like below.The problem is I can successfully instantiate class C. When I check the type and value of C.A it was very surprising for me.Briefly , I have following classes which are working ! My questions are : How can this be possible ? At which level does CLR ch... | public class A { } public class B { } var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly ( new AssemblyName ( `` Some.Namespace '' ) , AssemblyBuilderAccess.Run ) ; var moduleBuilder = assemblyBuilder.DefineDynamicModule ( assemblyBuilder.GetName ( ) .Name ) ; // public class Cvar typeBuilder = moduleB... | How can Reflection.Emit assign incompatible types ? |
C# | I am trying to get the latest contact with a given user , grouped by user : The user 's contact info could either be in SentTo or SentFrom . would give me the latest message , but I need the last message per user.The closest solution I could find was LINQ Max Date with group by , but I cant seem to figure out the corre... | public class ChatMessage { public string SentTo { get ; set ; } public string SentFrom { get ; set ; } public string MessageBody { get ; set ; } public string SendDate { get ; set ; } } List < ChatMessage > ecml = new List < ChatMessage > ( ) ; var q = ecml.OrderByDescending ( m = > m.SendDate ) .First ( ) ; | How do I group on one of two possible fields using LINQ ? |
C# | Sometimes , during development phase , I need to see if e.g . a name is changed for each element created or just wish to differentiate between different instances ' names in an array . That behavior is strictly for development-stage and only to be applied during a short period of time ( hence no need to long term solut... | int counter = 1 ; IEnumerable < Typo > result = originals.Select ( original = > new Thingy { Name = `` Hazaa '' + counter++ } ) ; | How to count without a counter in a select ? |
C# | I 'm getting a massive payload of XML from my WCF service , and I need to write it into a SQL database . I 'm using the latest version of .NET and Entity Framework 6 . `` Okay , that 's great , '' you may say , `` but what 's the question ? `` Well , the XML is being deserialized into C # objects ( generated from paste... | public ICollection < object > GetObjects ( ) { List < object > objs = new List < object > ( ) ; foreach ( var i in XmlObject.SubObj.SubObj.SubObj ) { objs.Add ( new MyEfObject ( ) { Prop1 = XmlObject.SubObj.SubObj.SubObj.ObjProperty // If `` ObjProperty '' is null , // I get a null reference exception } ) ; } return ob... | Ignoring null references when de-serializing a massive XML document |
C# | When doing this in C # : The compiler complains that `` the type or namespace 'Word ' could not be found '' . Is this not possible ? If it makes a difference , I 'm trying to do this in the global namespace.EDIT : just found another SO that answers this : Why can one aliased C # Type not be accessed by another ? This c... | using Word = System.String ; using Words = System.Collections.Generic.List < Word > ; | Can a type alias refer to another type alias ? |
C# | I have an string array containing names like : That I convert to a List < string > Then I need to write a function that returns the max repeated item in the list but should be sorted in descending order , which in this case , Michael.I have followed the LINQ code stated in this link . Which is : However , code returns ... | [ Alex , Alex , Michael , Michael , Dave , Victor ] string maxRepeated = prod.GroupBy ( s = > s ) .OrderByDescending ( s = > s.Count ( ) ) .First ( ) .Key ; string maxRepeated = prod.GroupBy ( s = > s ) .OrderByDescending ( s = > s.Count ( ) ) .OrderByDescending ( b = > b ) .First ( ) .Key ; | LINQ Return max repeated item but sorted in reverse |
C# | I have a panel ViewStock where i am viewing stock in a gridview from database and DataBind ( ) it via code . Allowed paging and created and event `` OnPageIndexChanging '' in gridview tag in html , Implemented the defined code above and paging in an event as follows : HTML : Code C # : And now the Implemented Pagingit ... | < asp : Panel ID= '' Panel_StockView '' runat= '' server '' > < asp : GridView ID= '' GridView_Stock '' AllowPaging= '' true '' OnPageIndexChanging= '' GridView_PageIndexChanging '' runat= '' server '' > < /asp : GridView > < /asp : Panel > protected void LinkButton_Panel_ViewStock_Click ( object sender , EventArgs e )... | GridView do n't Show on GridView_PageIndexChanging |
C# | I have to create a method that verify if a number follow a certain structure , and it must follow a existing pattern implemented in PHP , but I 'm having certain trouble doing thins in C # .NET . When the number went too long I got a System.OverflowException , I 'm using ulong , take a look : And I have to reproduce th... | /// < summary > /// Gera um dígito verificador para um código /// < /summary > /// < param name= '' code '' > Código < /param > /// < returns > Digito verificador < /returns > public static ulong GenerateTrustID ( UInt64 code ) { UInt64 intcode = 1 ; UInt64 endcode = 0 ; foreach ( UInt64 number in code.ToString ( ) .To... | Big number in C # .NET |
C# | I am working on alpha.dubaiexporters.com . There is a search Panel containing two inputs Keyword and Categories . I wanted to validate Keyword part.If the user entered less than three characters and clicked on Search button then the clientside message should be displayed saying the entered input should be more than 3 c... | < input type= '' text '' id= '' txtkeyword '' name= '' s '' runat= '' server '' autocomplete= '' off '' > < asp : Button ID= '' Search '' class= '' dt-header-search-submit dt-button dt-button-danger '' style= '' top:0px ; width:226px ; height:70px ; '' Text= '' Search '' runat= '' server '' onclick= '' doit '' OnClient... | Not getting the clientside message after clicking on Search button |
C# | Consider the following IDisposable class : Every method in this class , including Dispose ( ) , should begin with a check like this : Since it is tedious and repetitive to write this in all methods , I would like to use contract invariant : However , this only ensures IsDisposed is false at the end of each public metho... | class MyClass : IDisposable { public bool IsDisposed { get ; private set ; } = false ; public void Dispose ( ) { IsDisposed = true ; } } if ( IsDisposed ) { throw new ObjectDisposedException ( ... ) ; } public class MyClass : IDisposable { ... [ ContractInvariantMethod ] private void objectInvariant ( ) { Contract.Inva... | Using invariant for IDisposable |
C# | I have this : and I am just saying if the value is above 10 then change it to 255.But , it is quite slow.Is there a quicker way to do the above ? | var data = new byte [ 100,100,1 ] ; //data is populated from external sourcefor ( var h = 0 ; h < 100 ; h++ ) { for ( var w = 0 ; w < 100 ; w++ ) { if ( Data [ h , w , 0 ] > 10 ) { Data [ h , w , 0 ] = 255 ; } } } | Faster way to manipulate mutli byte array |
C# | Below I have a solution to get attributes from fields with an extension method . Now I want to do a similar thing with methods instead of fields.Usage : So in my case the usage should look something like this : Is this possible in any way or do I have to try something completely different ? | public static MemberInfo GetMember < T , R > ( this T instance , Expression < Func < T , R > > selector ) { var member = selector.Body as MemberExpression ; return member ? .Member ; } public static T GetAttribute < T > ( this MemberInfo meminfo ) where T : Attribute { return meminfo.GetCustomAttributes ( typeof ( T ) ... | Accessing attributes on methods using extension method |
C# | I 've designed a Windows Forms dialog that should be reusable in other applications , WPF and Windows Forms . This works fine when I use it in a Windows Forms application , but it causes some layout trouble when called in a WPF application . Dimensions and sizes are inconsistent when measured from the pixels on the scr... | using System ; using System.Drawing ; using System.Windows.Forms ; namespace DialogTestApp { internal class MyDialog : Form { public MyDialog ( ) { Text = `` Title '' ; Width = 500 ; // - > actually 510 ( Spy++ says 500 ) Height = 300 ; // - > actually 310 ( Spy++ says 300 ) Font = SystemFonts.MessageBoxFont ; FormBord... | Dialog has unrequested additional space |
C# | I am running this code in Unity ( Mono backend with .Net 4.x ) In Debugging ( with Visual Studio ) , compare1 is false while compare2 is true.How is this happening ? Why are the last two lines different ? I would think that sum == a + b . | float a = 0.42434249394294f ; float b = 1 - a ; float sum = a + b ; bool compare1 = ( a + b ) > = 1f ; bool compare2 = sum > = 1f ; | Comparing the sum of floats |
C# | I want to ask , can you do something similar to this ? Event is a classI want to do something similar to delegates : Thanks . | Event += eventInstance ; Write write1 = new Write ( ( ) = > Console.WriteLine ( `` Write1 '' ) ) ; Write write2 = new Write ( ( ) = > Console.WriteLine ( `` Write2 '' ) ) ; Write write3 = new Write ( ( ) = > Console.WriteLine ( `` Write3 '' ) ) ; Write write = write1 + write2 + write3 ; write ( ) ; | C # adding objects ( similar to delegates ) |
C# | The goalChange the model depending on what it is expecting.The problemI have a method in my ProductsControllercalled Category . When someone request this method , two things can happen : if the parameter passed to the method is different than Daily-Offers , then one type of list is passed to View . If the parameter pas... | [ HttpGet ] public ActionResult Category ( string categoryName = null ) { int ? categoryId = categoryName ! = `` Daily-Offers '' ? Convert.ToInt32 ( Regex.Match ( categoryName , @ '' \d+ '' ) .Value ) : ( int ? ) null ; if ( categoryName == `` Daily-Offers '' ) { var productsList = Products.BuildOffersList ( ) ; ViewBa... | Set the model depending on what it is expecting in view |
C# | N.B . refer to this link.I wrote this class to be used as a proxy in the server-end and as a client at the client-end.My current source code is the following : The problem I am facing with this code is : are going to the other end as only one input : , rather than three separate inputs { `` 1 '' , `` 2 '' , and `` hell... | public class ClientClass : IDisposable { private string Host { get ; set ; } private int Port { get ; set ; } public bool IsConnected { private set ; get ; } public TcpClient Tcp { get ; private set ; } private System.Net.Sockets.NetworkStream stream ; public ClientClass ( ) { IsConnected = false ; } //constructor for ... | Different data written to the server are becoming appended to become a single string |
C# | I 'm making a program with multiple types of binary trees in it . So I decided to make an abstract class , to avoid copying code over . But there is a problem , the nodes of each tree need to contain children that are the same type as the node itself . Is there any means to define this in the abstract , or should I jus... | public abstract class BinaryNodeAbstract < T > { public T Value ; public BinaryNodeAbstract < T > Left ; public BinaryNodeAbstract < T > Right ; | Abstract with inheritor as field |
C# | Say I have the elements with the ID 's of `` Input1 '' , `` Input2 '' and `` Input3 '' .Is there a way to loop through them rather then having to write : in jquery you can just refrence an element like $ ( ' # Input'+i ) and loop through i , something similar would be very useful in ASP code behind . | Input1.Value = 1 ; Input2.Value = 1 ; Input3.Value = 1 ; | Can we dynamically reference element ( Server Side ) |
C# | I have the following function which is intended to `` memoize '' argument-less functions . Meaning to only call the function once , and then return the same result all other times.Can I be certain that if a thread reads `` inited == true '' outside the lock , it will then read the `` value '' which was written before `... | private static Func < T > Memoize < T > ( Func < T > func ) { var lockObject = new object ( ) ; var value = default ( T ) ; var inited = false ; return ( ) = > { if ( inited ) return value ; lock ( lockObject ) { if ( ! inited ) { value = func ( ) ; inited = true ; } } return value ; } ; } | Memory read visibility ordering vs write order using double-checked locking |
C# | I am using TPL blocks to carry out operation that may be cancelled by user : I have come up with two options , in first I cancel whole block but do n't cancel operation inside the block , like this : and the second I cancel inside operation , but not the block itself : As I understand , first option will cancel whole b... | _downloadCts = new CancellationTokenSource ( ) ; var processBlockV1 = new TransformBlock < int , List < int > > ( construct = > { List < int > properties = GetPropertiesMethod ( construct ) ; var entities = properties .AsParallel ( ) .Select ( DoSometheningWithData ) .ToList ( ) ; return entities ; } , new ExecutionDat... | Correct way to cancel TPL data flow block |
C# | In TypeScript I can declare an array such as : Is there a shorthand way I could do something similar in C # ? I find myself mutating and mapping lists a lot and it gets cumbersome to explicitly declare classes and interfaces for each different operation . | const arr : { id : number ; value : string ; } [ ] = [ ] ; var list = new List < { int id ; string value ; } > ( ) ; | Inline/shorthand types in C # |
C# | I have a class : From a List < Point > , say I want the Point where Point.X + Point.Y is maximum in the list . How would I do this in LINQ ? | class Point { double X , Y ; } | Return the element of a list which fulfills a certain condition |
C# | I ca n't believe how frustratingly difficult I 'm finding such a simple task.I want to create a link with a page query argument.I tried the following : And here 's the link that is generated.I 've been Googling for an hour . Can anyone tell me the Razor Pages way to create a link with a query argument ? Also , is there... | < a asp-page= '' Index '' asp-route-page= '' 10 '' > Character Classifications < /a > < a href= '' / '' > Character Classifications < /a > | Razor page link ignores route argument |
C# | I 'm using Task to process multiple requests in parallel and passing a different parameter to each task but it seems all the tasks takes one final parameter and execute the method using that.Below is the sample code . I was expecting output as : 0 1 2 3 4 5 6 ..99 but I get : 100 100 100 ..10 . May be before print meth... | class Program { static void Main ( string [ ] args ) { Task [ ] t = new Task [ 100 ] ; for ( int i = 0 ; i < 100 ; i++ ) { t [ i ] = Task.Factory.StartNew ( ( ) = > print ( i ) ) ; } Task.WaitAll ( t ) ; Console.WriteLine ( `` complete '' ) ; Console.ReadLine ( ) ; } private static void print ( object i ) { Console.Wri... | Why would Task object not use parameter passed to it ? |
C# | If i have 3 DateTime lists that come from different sourcesWhat would be the quickest way to return a list of DateTime that exist in all 3 of the lists . Is there some LINQ statement ? | List < Datetime > list1 = GetListOfDates ( ) ; List < Datetime > list2 = GetAnotherListOfDates ( ) ; List < Datetime > list3 = GetYetAnotherListOfDates ( ) ; | What is the easiest way to seeing if there are any matches across a few DateTime arrays ? |
C# | I have tried the solutions I have found and can not seem to make this work for me.I have a class : I make a call to a service : And now I want to sort the Reports list in callResponse by CompletedDatecallResponse.Reports.Sort ( ( x , y ) = > DateTime.Compare ( x.CompletedDate , y.CompletedDate ) ) ; This returns an err... | public class InvokeGetReportRequestListResponse { public MarketplaceWebServiceException Error { get ; set ; } public bool CallStatus { get ; set ; } public List < RequestedReport > Reports { get ; set ; } } public class RequestedReport { public String ReportRequestId ; public String ReportType ; public DateTime ? Start... | Sorting List by DateTime |
C# | Suppose I have a class : And an extension method : What would be the most convenient way to remove the FooExtensions class and alter Foo so it becomes : ReSharper does n't seem to offer a one-step action to do this ( strangely enough as this seems a pretty straightforward refactoring ) , but which other actions might I... | public class Foo { public int Bar { get ; set ; } } public static class FooExtensions { public static void DoSomething ( this Foo foo , int someNumber ) { foo.Bar += someNumber ; } } public class Foo { public int Bar { get ; set ; } public void DoSomething ( int someNumber ) { Bar += someNumber ; } } | Converting extension methods to instance methods with ReSharper ? |
C# | I am sending the Json format like this in PostManIn controller level i am doing the validation of all fields.After validation how can i convert the above json string to below formatAnd aftre converting , i want to insert to database.How to convert in c # ? Please help me.And the below code is the class for students : A... | { `` number '' : 2106887 , `` date '' : `` 09/10/2018 '' , `` degree '' : '' BE '' `` Students '' : [ { `` Branch '' : `` ABK015 '' , `` Doc '' : `` NCE '' , `` Description '' : `` Testing '' , `` dni '' : `` 1016035232 '' , `` Name '' : `` ABCE '' , `` Gender '' : `` M '' , `` Title '' : `` Univercity '' , `` email ''... | How can i change the json formate after request in c # ? |
C# | I have two grids on my form . Whenever a row gets focus in grid1 , its associated children rows are fetched from the database via ADO.NET and grid2 's DataSource is reassigned as follows : ASIDE : grid1 contains many rows so I do n't want to fetch the children rows for all of the parent rows in one ( time-consuming ) q... | //focused row changed handler DataTable Children = FetchChildren ( parentid ) ; grid2.DataSource = Children.DefaultView ; Children.RowDeleted += ( sndr , evt ) = > { // } ; | Will reassigning datasource cause a memory leak if listeners are not removed first ? |
C# | This class declaration : Can not be fulfilled by this class signature : Where SqlEntity : IEntity and SqlDataProvider : DataProvider < SqlEntity > , I get this error : Error 1 The type ~ can not be used as type parameter 'TD ' in the generic type or method '~.Repository ' . There is no implicit reference conversion fro... | public abstract class Repository < TE , TD > where TE : class , IEntity , new ( ) where TD : DataProvider < TE > public class SqlRepository < TE > : Repository < TE , SqlDataProvider > where TE : SqlEntity , new ( ) | Can not inherit with generics |
C# | Is there a way to add a attribute or something to a class that whenever a property of that class gets called that a method will be called ? Basically i have classes that contains a datarow and instead of accessing the individual column like : ( DataRow [ `` some_column_name '' ] ) I want to access them using properties... | public string some_column_name { get { return ( string ) GetValue ( MethodBase.GetCurrentMethod ( ) .Name ) ; } set { SetValue ( MethodBase.GetCurrentMethod ( ) .Name , value ) ; } } private DataRow some_table ; protected object GetValue ( string columnName ) { return some_table [ columnName.Substring ( columnName.Inde... | Call a method whenever a property is called |
C# | I 've got a form with a submit button , and I want to show a dialog before continuing the form submission . The code below is showing the dialog properly , but it continues the submit anyway : | @ using ( Html.BeginForm ( `` SubmitForm '' , `` Home '' , FormMethod.Post , new { id = `` form '' } ) ) { @ Html.AntiForgeryToken ( ) *snip* < div class= '' collapseClosed panel-footer panel-collapse collapse in '' > < input type= '' submit '' name= '' btnSubmit '' id= '' btnSubmit '' class= '' btn btn-success '' valu... | How can I show a dialog before submitting ? |
C# | For a library ( .NET Standard 2.0 ) , I designed some classes that look roughly like this : The classes were criticized because of that `` MyContext '' parameter that every constructor requires.Some people say that it clutters the code.I said that the parameter is needed to propagate the context , so that e.g . when yo... | public class MyContext { // wraps something important . // It can be a native resource , a connection to an external system , you name it . } public abstract class Base { public Base ( MyContext context ) { Context = context ; } protected MyContext Context { get ; private set ; } // methods } public class C1 : Base { p... | Passing the context around in a C # class library , looking for an `` easy '' way without using static |
C# | I have a method like this in my libraryI want to refactor it and remove the generic parameter.How does it affect the code dependent on my library ? Do they need to do a rebuild ? Do they encounter compile error ? What if they have used reflection to call this method ? If I create both of them then the method resolution... | public void Foo < T > ( IQueryable < T > input ) { //T is never used and the code compiles when I remove T } public void Foo ( IQueryable input ) { ... } | Removing generic parameter from method signiture |
C# | I am just wandering if the following is possible in C # .Let 's say I have a List-like interface that mandates the operation reverse . I.e . : However , now when I go and implement that interface : I am still forced to use the interface ReversableList . So even if the user were to instantiate my ListImplementation dire... | public interface ReversableList < T > { // Return a copy of this list but reversed ReversableList < T > Reverse ( ) ; // We still need to return the contained type sometimes T Get ( int index ) } public class ListImplementation < T > : ReversableList < T > ReversableList < T > Reverse ( ) ; } var concreteList = new Lis... | Allow implementing classes to use themselves as types |
C# | I have an array of MyClass , which can be simplified as follow : Now , in the Array , without any errors from the user side or throughout the input process , there can not be MyClass instance with identical Id and Origin . However , if there be any , I should resolve it . And here are the resolving rules : Firstly by P... | public class MyClass { public int Id ; public string Origin ; public int Points ; public DateTime RequestTime ; public MyClass ( int id , string origin , int points , DateTime requestTime ) { Id = id ; Origin = origin ; Points = points ; RequestTime = requestTime ; } } MyClass [ ] myarr = new MyClass [ ] { new MyClass ... | LINQ Solution for Multiple Resolves |
C# | I got stuck with attempt of generic casting or building a LINQ expression that could be casted to the required generic type T.Here is the failing example : Is there any way to cast T or build a Linq expression that would treat T as ICompanyLimitedEntity and execute the query on the SQL server ? | public override void PreprocessFilters < T > ( ISpecification < T > specification ) { if ( typeof ( ICompanyLimitedEntity ) .IsAssignableFrom ( typeof ( T ) ) ) { var companyId = 101 ; // not relevant , retrieving company ID here // and now I need to call the method AddCriteria on the specification // as it were ISpeci... | Casting generic type to build a valid Linq expression |
C# | Something is dropping my running tasks beyond a certain point in the code ( see where below ) . It just stops executing . It only happens on iOS devices . On iOS simulators and android devices it runs perfectly . Anyone seen anything like this before ? I do n't think it 's deadlocks or race conditons , because then it ... | private async Task ExecuteFreshAndPopulateUI ( IFetchVehicleCommand command ) { List < Models.Vehicle.Vehicle > vehicles = await command.ReturnAndExecute < Models.Vehicle.Vehicle > ( ) ; var z = 9 ; ListPopulateObservableCollection ( vehicles , view.Vehicles ) ; } public virtual async Task < dynamic > ReturnAndExecute ... | iOS dropping Tasks in the middle of execution |
C# | I have a UserControl which a couple of buttons and some Textblock 's . For some reason , the TextWrap is not working for this Textblock.The output ( The selected part = second StackPanel ) while the part where I have the mouse = the second textblock with the TextWrapping property set to Wrap.See here | < StackPanel Grid.Column= '' 0 '' Margin= '' 0 0 0 10 '' > < TextBlock FontWeight= '' DemiBold '' Text= '' Account closure '' x : Name= '' Message '' Margin= '' 0 6 0 2 '' FontSize= '' 18 '' / > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' A random text here , here , here `` Margin= '' 0 6 0 0 '' F... | TextWrap in StackPanel |
C# | I have a methodand the idea is to use it this wayhowever it is an error to create a nested expression even though the compiler will accept itnow I can catch this at runtime by parsing the expression tree . For exampleI was wondering however , is there any clever way to detect this at compile time ? I doubt it because t... | public static class PropertyLensMixins { public static ILens < Source > PropertyLens < O , Source > ( this O o , Expression < Func < O , Source > > selector ) where O : class , INotifyPropertyChanged where Source : class , Immutable { return new PropertyLens < O , Source > ( o , selector ) ; } } this.PropertyLens ( p= ... | Is it possible to statically verify structure of c # expression tree arguments ? |
C# | I have been thinking about this problem for a while and it feels like there must be a simple solution that I 'm missing.Let 's say I have the following class : If I get all constructors on the type Foo < System.Int32 > I will get back two constructors , both with a single parameter of type System.Int32 which can not be... | public class Foo < T > { public Foo ( T value ) { } public Foo ( int value ) { } } // Will return two constructors with signatures that look identical . var type = typeof ( Foo < int > ) ; var ctors1 = type.GetConstructors ( ) ; // Will return two constructors as well . Parameters can be differentiated.var genericTypeD... | Matching constructor to counterpart in generic type definition |
C# | I made my own SQL string that uses INNER JOINS . Here is my function : Now the problem is , when I click one Item on the stocksList ListView the recipeList ListView would have multiple values . Like 5 or so rows of the same values . | string cmdstr = @ '' SELECT s.* , mdb.menu_name FROM stocksdb s , recipelist rl INNER JOIN menudb mdb ON rl.menu_ID = mdb.menu_ID WHERE rl.stock_ID = ' '' + stockID + `` ' '' ; var cmd = new MySqlCommand ( cmdstr , db.mycon ) ; var dr = cmd.ExecuteReader ( ) ; while ( dr.Read ( ) ) { var menuname = dr [ `` menu_name ''... | Duplicating values because of SQL string ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.