lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have a parent object that has a reference to a child object and additionally the parent has an event handler that listens to an event of the child object.If all references to the parent object will be released , will the memory used through the parent and the child be freed through GC ? ( Assuming that no more refere... | class ParentClass { ChildClass _childClass ; public ParentClass ( ChildClass childClass ) { _childClass = childClass ; childClass.SomeEvent += ChildClass_SomeEvent ; } void ChildClass_SomeEvent ( object sender , SomeEventArgs e ) { } } | Will GC release used memory |
C# | I 'm working on a game here , and found this rather intriguing bug . Suppose you have this enum : a base classand two instances of it : This is what happened to me : The first instance 's type would remain as pre-initialized in the base class , even though I specified in its constructor that I want the type to be Food.... | public enum ItemType { Food , Weapon , Tools , Written , Misc } ; public class BaseItem { public string Name = `` Default Name '' ; public ItemType Type = ItemType.Misc ; } Ins1 = new BaseItem { Name = `` Something '' , Type = ItemType.Food } ; Ins2 = new BaseItem { Name = `` Something too '' , Type = ItemType.Tools } ... | Strange behavior with C # enums |
C# | Just wondered why the discrepancy really . : -/ | //okAction < int > CallbackWithParam1 = delegate { } ; //error CS1593 : Delegate 'System.Action < int > ' does not take 0 argumentsAction < int > CallbackWithParam2 = ( ) = > { } ; | Why can anonymous delegates omit arguments , but lambdas ca n't ? |
C# | I 'm trying my hand at behavior driven development and I 'm finding myself second guessing my design as I 'm writing it . This is my first greenfield project and it may just be my lack of experience . Anyway , here 's a simple spec for the class ( s ) I 'm writing . It 's written in NUnit in a BDD style instead of usin... | [ TestFixture ] public class WhenUserAddsAccount { private DynamicMock _mockMainView ; private IMainView _mainView ; private DynamicMock _mockAccountService ; private IAccountService _accountService ; private DynamicMock _mockAccount ; private IAccount _account ; [ SetUp ] public void Setup ( ) { _mockMainView = new Dy... | Is this a poor design ? |
C# | System.Array serves as the base class for all arrays in the Common Language Runtime ( CLR ) . According to this article : For each concrete array type , [ the ] runtime adds three special methods : Get/Set/Address.and indeed if I disassemble this C # code , into CIL I get , where the calls to the aforementioned Get and... | int [ , ] x = new int [ 1024,1024 ] ; x [ 0,0 ] = 1 ; x [ 1,1 ] = 2 ; x [ 2,2 ] = 3 ; Console.WriteLine ( x [ 0,0 ] ) ; Console.WriteLine ( x [ 1,1 ] ) ; Console.WriteLine ( x [ 2,2 ] ) ; IL_0000 : ldc.i4 0x400IL_0005 : ldc.i4 0x400IL_000a : newobj instance void int32 [ 0 ... ,0 ... ] : :.ctor ( int32 , int32 ) IL_000f... | Where can I find information on the Get , Set and Address methods for multidimensional System.Array instances in .NET ? |
C# | Given event store with fields : AggregateId : integerPayload : blobVersion : integerWhich contains events based on : ... and then has further events added with an updated structure : When this historical data is retrieved ( for analysis , etc ) , how do you reconstruct binary payload into meaningful data ? Note : the c... | public class OrderLineAdded { int Id ; short Quantity ; } public class OrderLineAdded { int ProductId ; // field name has changed int Quantity ; // field datatype has changed } | How to retrieve historical events after changes to Domain Event structure |
C# | How can I get Visual Studio to provide controller and action syntax highlighting like it offers for its own object for controller and action strings in the following ? When you use : Visual Studio provides additional highlighting on the controller and action , it even tries to detect which ones are available and will p... | Html.Action ( `` Index '' , `` Home '' ) ; public static MvcHtmlString Action ( this HtmlHelper htmlHelper , string actionName , string controllerName , string myAwesomeField ) { return Action ( htmlHelper , actionName , controllerName , null /* routeValues */ , myAwesomeField ) ; } | How to get syntax highlighting of controllers and actions on HtmlHelper extension method ? |
C# | I 'm trying to create a Generic Action Delegate andand here is my callerand here is the business objectand here is the error what i get during compilationMy GetSetterAction is returning ActionPerdicate where as here T is busPerson and i am trying to store it in ActionPredicate keeping in mind about Contravariance . But... | delegate void ActionPredicate < in T1 , in T2 > ( T1 t1 , T2 t2 ) ; public static ActionPredicate < T , string > GetSetterAction < T > ( string fieldName ) { ParameterExpression targetExpr = Expression.Parameter ( typeof ( T ) , `` Target '' ) ; MemberExpression fieldExpr = Expression.Property ( targetExpr , fieldName ... | Contravariance in Expressions |
C# | I thought that ^ did that.I expected : What I 'm gettingthe actual code isreplacing exp for 0 , 1 , and 2What does the ^ operator do ? | 10^0=110^1=1010^2=100 10^0=1010^1=1110^2=8 int value = 10 ^ exp ; | What does ^ operator do ? |
C# | I came across this situation where the following plinq statement inside static constructor gets deadlocked : It happens only when a constructor is static.Can someone explain this to me please.Is it TPL bug ? Compiler ? Me ? | static void Main ( string [ ] args ) { new Blah ( ) ; } class Blah { static Blah ( ) { Enumerable.Range ( 1 , 10000 ) .AsParallel ( ) .Select ( n = > n * 3 ) .ToList ( ) ; } } | Plinq statement gets deadlocked inside static constructor |
C# | Total OO noob question here . I have these two methods in a class And when I call StoreSessionSpecific with dbSession being of type LateSession ( LateSession inherits Session ) I expected the top one to be called . Since dbSession is of type LateSession . @ Paolo Tedesco This is how the classes are defined . | private void StoreSessionSpecific ( LateSession dbSession , SessionViewModel session ) { session.LateSessionViewModel.Guidelines = dbSession.Guidelines.ToList ( ) ; } private void StoreSessionSpecific ( Session dbSession , SessionViewModel session ) { // nothing to do yet ... } var dbSession = new LateSession ( ) ; Sto... | Why is n't the most specific method called based on type of parameter |
C# | My ultimate goal here is to turn the following string into JSON , but I would settle for something that gets me one step closer by combining the fieldname with each of the values.Sample Data : Using Regex.Replace ( ) , I need it to at least look like this : Ultimately , this result would be awesome if it can be done vi... | Field1 : abc ; def ; Field2 : asd ; fgh ; Field1 : abc , Field1 : def , Field2 : asd , Field2 : fgh { `` Field1 '' : '' abc '' , '' Field2 '' : '' asd '' } , { `` Field1 '' : '' def '' , '' Field2 '' : '' fgh '' } ( ? : ( \w+ ) : ) * ? ( ? : ( [ ^ : ; ] + ) ; ) EDIT : string hbi = `` Field1 : aaa ; bbb ; ccc ; ddd ; Fi... | Need some help on a Regex match / replace pattern |
C# | Conversion failed when converting the varchar value 'DADE ' to data type int.SQL command which i use is this : My code is : | SELECT * FROM p_details WHERE LOWER ( name ) LIKE ' % has % ln % ' AND CODE = 13 AND T_CODE= ' H ' SqlDataReader drr = com4.ExecuteReader ( ) ; DataTable dt = new DataTable ( ) ; dt.Load ( drr ) ; < -- error lineGridView7.DataSource = dt ; GridView7.DataBind ( ) ; | Error when data is bind into data table or gridview |
C# | I 've been having this problem for awhile in Visual Studio 2013 . It does n't seem to understand how to apply the indentation rules properly to lambda expressions when they 've been lined up incorrectly . Here is a simplified example : In the second and third row , the indent is only 3 spaces instead of 4 ( the real co... | var s = new Action ( ( ) = > { } ) ; | Incorrect Lambda Expression Indentation |
C# | We have an entity in our system called an `` identity program . '' That is also our sharding boundary , every identity program is stored in its own shard , so the identifier of the shard is the identifier of the identity program.We are in the process of implementing the ability to physically delete an identity program ... | var shardKey = new Guid ( `` E03F1DC0-5CA9-45AE-B6EC-0C90529C0062 '' ) ; var connectionString = @ '' shard-catalog-connection-string '' ; var shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager ( connectionString , ShardMapManagerLoadPolicy.Lazy ) ; var shardMap = shardMapManager.GetListShardMap < Guid > ( `... | Can not delete shard mapping using Azure SQL Elastic Scale |
C# | I have an method that throws exception : I 'm using this method in more than 100 places in my code , the problem is when i use this method in another method that must return a value Re-sharper dose not understands that there is no need for returning a value , for example : is there any way to tell Re-sharper that MyMet... | public void MyMethod ( ) { // do some logging throw new Exception ( `` My Text '' ) ; } public int AnotherMethod ( ) { // some stuff MyMethod ( ) ; // < = it always throws exception return 0 ; // i have to put this code , while it never executes } public int AnotherMethod ( ) { // some stuff throw new Exception ( ) ; /... | How could i let Resharper or Intellisense know that a method allwayse throws exception ? |
C# | First some information about my development environment : .Net Framework 4.5Moq 4.10Autofac 4.2NUnit 3.11I try to mock a function that takes some string arguments and I would like to use It.IsAny < string > ( ) to setup . Normally I would to that like this : But now I would like to call a fucntion that makes the setup ... | using ( AutoMock mock = AutoMock.GetLoose ( ) ) { mock.Mock < SomeInterface > ( ) .Setup ( x = > x.someFunction ( It.IsAny < string > ( ) , It.IsAny < string > ( ) , It.IsAny < string > ( ) ) ) ; // ... } using ( AutoMock mock = AutoMock.GetLoose ( ) ) { UnknownType anyString = It.IsAny < string > ( ) ; setup ( mock , ... | Passing Moqs It.IsAny < string > as method argument |
C# | I 'm tring to create a class which does all sorts of low-level database-related actions but presents a really simple interface to the UI layer.This class represents a bunch of data all within a particular aggregate root , retrieved by a single ID int.The constructor takes four parameters : The UI layer accesses this cl... | public AssetRegister ( int caseNumber , ILawbaseAssetRepository lawbaseAssetRepository , IAssetChecklistKctcPartRepository assetChecklistKctcPartRepository , User user ) { _caseNumber = caseNumber ; _lawbaseAssetRepository = lawbaseAssetRepository ; _assetChecklistKctcPartRepository = assetChecklistKctcPartRepository ;... | Architecture problem : use of dependency injection resulting in rubbish API |
C# | The following F # code declares base and descendant classes . The base class has a virtual method 'Test ' with a default implementaion . The descendant class overrides the base class method and also adds a new overloaded 'Test ' method . This code compiles fine and presents no issues when accessing either of the descen... | module OverrideTest [ < AbstractClass > ] type Base ( ) = abstract member Test : int - > int default this.Test x = x + 1 type Descendant ( ) = inherit Base ( ) override this.Test x = x - 1 member this.Test ( x , y ) = x - y using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namesp... | Can not resolve an F # method that has been both overridden and overloaded from C # |
C# | I 'm trying to create a MediaComposition . I have succeeded in combining multiple png images into a single video ; however , the files that 's created has a black background . At first I thought this might be because the files were png files , but the same bevaviour occurs for jpgs . The following is how I 'm saving th... | public async Task < bool > Save ( InkCanvas canvas , StorageFile file ) { if ( canvas ! = null & & canvas.InkPresenter.StrokeContainer.GetStrokes ( ) .Count > 0 ) { if ( file ! = null ) { using ( IRandomAccessStream stream = await file.OpenAsync ( FileAccessMode.ReadWrite ) ) { await canvas.InkPresenter.StrokeContainer... | Add a background colour to a MediaComposition |
C# | I have a function that makes a list of animals , some of which are dogs , and some of which are just animals . That function returns that list to a different function that wants to extract out just the dogs , which is possible because the Animal class has a bool isDog . My question is , is it possible to extract the do... | public interface IAnimal { string eyeColor ; int numLegs ; } public interface IDog : IAnimal { double tailLength ; } public class Animal : IAnimal { public string eyeColor { get ; set } public int numLegs { get ; set ; } public bool isDog ; public Animal ( string eyes , int legs ) { this.eyeColor = eyes ; this.numLegs ... | When a Child class is added to a List < parent > , is the child-specific data lost ? |
C# | I have following entity : What I need is to create optional-to-optional relationship within the same entity using PreviousRevision as a navigation property and PreviousRevisionId as a foreign key Id for it.I know that it can be done by annotating PreviousRevisionId property with [ ForeignKey ( `` PreviousRevision '' ) ... | public class Revision { public int Id { get ; set ; } ... public int ? PreviousRevisionId { get ; set ; } public virtual Revision PreviousRevision { get ; set ; } } HasOptional ( c = > c.PreviousRevision ) .WithOptionalDependent ( ) .Map ( m = > m.MapKey ( `` PreviousRevisionId '' ) ) ; | EF6.1 optional-to-optional with fluent api mapping |
C# | First - a disclaimer : If you 're reading this because you want to use both a binding for IsChecked and a RelayCommand to change things , you probably are doing it wrong . You should be working off of the IsChecked binding 's Set ( ) call.The question : I have a ToggleButton in which there 's both a binding for IsCheck... | < ToggleButton IsChecked= '' { Binding BooleanBackedProperty } '' Command= '' { Binding SomeCommand , RelativeSource= { RelativeSource FindAncestor , AncestorType= { x : Type Window } } } '' CommandParameter= '' { Binding } '' / > | What executes first : ToggleButton.IsChecked binding update , or Command binding ? |
C# | I was trying to find out if setting the capacity of a list in the constructor could flatten the already negligible performance differences between using List < T > ( IEnumerable < T > ) vs List < T > ( ) + AddRange ( IEnumerable < T > ) .I found out setting the capacity before AddRange ( ) actually leads to roughly the... | int items = 100000 ; int cycles = 10000 ; var collectionToCopy = Enumerable.Range ( 0 , items ) ; var sw0 = new Stopwatch ( ) ; sw0.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( collectionToCopy ) ; } sw0.Stop ( ) ; Console.WriteLine ( sw0.ElapsedMilliseconds ) ; var sw1 = ne... | Performance difference with various List initialization and population techniques |
C# | I have a method that is looping through a list of values , what I would like to do is when I open the page to be able to see the values changing without refreshing the current view . I 've tried something like the code bellow.The actual thing is I want it to read this values even if I close the form . I presume I would... | public static int myValueReader { get ; set ; } public static void ValueGenerator ( ) { foreach ( var item in myList ) { myValue = item ; Thread.Sleep ( 1000 ) ; } } | How to display different values without refreshing the page MVC C # |
C# | for access control purposes in a intensive DB use system I had to implement an objectset wrapper , where the AC will be checked.The main objective is make this change preserving the existing code for database access , that is implemented with linq to entities all over the classes ( there is no centralized layer for dat... | public class ObjectSetWrapper < TEntity > : IQueryable < TEntity > where TEntity : EntityObject { private IQueryable < TEntity > QueryableModel ; private ObjectSet < TEntity > ObjectSet ; public ObjectSetWrapper ( ObjectSet < TEntity > objectSetModels ) { this.QueryableModel = objectSetModels ; this.ObjectSet = objectS... | ObjectSet wrapper not working with linqToEntities subquery |
C# | I 'm trying to fill a data grid view in my windows form application but nothing is being returned from the database when I execute the select query . I 've looked at other questions about this topic on this site but can not find anything that addresses my problem . The name of the data view table is qbcMemDataView and ... | public Form1 ( ) { InitializeComponent ( ) ; dbConnection = new SQLiteConnection ( `` Data Source=sqlite_db.sqlite ; Version=3 '' ) ; dbConnection.Open ( ) ; string [ ] restrictions = new string [ 4 ] ; restrictions [ 2 ] = `` test_table_mom '' ; using ( DataTable dTbl = dbConnection.GetSchema ( `` Tables '' , restrict... | SQLite Data Adapter not displaying data |
C# | I have a question regarding the symbol that separates days from hours in TimeSpan.ToString output.The standard TimeSpan format strings produce different separator symbols : '' c '' produces a period ( `` . '' ) character '' g '' and `` G '' produce a colon ( `` : '' ) characterExample : Does anybody know what 's the lo... | // Constant formatConsole.WriteLine ( TimeSpan.FromDays ( 42 ) .ToString ( `` c '' , CultureInfo.InvariantCulture ) ) ; // Output : 42.00:00:00 ( period character between days and hours ) // General short formatConsole.WriteLine ( TimeSpan.FromDays ( 42 ) .ToString ( `` g '' , CultureInfo.InvariantCulture ) ) ; // Outp... | Strange TimeSpan.ToString output |
C# | I am looking for a way to ensure that only serializable objects are stored into a Dictionary in C # .To be more specific I 'm looking to do something similar to this : The problem with this is that I can not store primitive types like integers , booleans , or strings.Is there a way to ensure that my Dictionary contains... | Dictionary < String , ISerializable > serialDict = new Dictionary < String , ISerializable > ( ) ; | Dictionary containing with only Serializable objects |
C# | I am using Dapper to call a stored procedure which have a mandatory parameter @ idProjectthis is my code fragment : Should work but raise an exception : An exception of type 'System.Data.SqlClient.SqlException ' occurred in System.Data.dll but was not handled in user code Additional information : Procedure or function ... | using ( var c = _connectionWrapper.DbConnection ) { var result = c.Query < Xxx > ( `` dbo.xxx_xxxGetPage '' , new { @ idProject = 1 } ) .AsList ( ) ; return result ; } | Mandatory parameters , Dapper and System.Data.SqlClient.SqlException |
C# | I 'm working on a relatively straight forward C # project that connects an Access Database via OleDb with various functions such as adding , deleting and editing records . Now , everything has worked fine up until trying to implement a database search . The following line ( in the searchbox code ) throws up the excepti... | ReturnedResults = DBDataSet.Tables [ `` Movies '' ] .Select ( `` Title like ' % '' + Search + `` % ' '' ) ; private void SearchTextBox_Changed ( object sender , EventArgs e ) { string SearchString = SearchTextBox.Text.ToString ( ) ; int Results = 0 ; DataRow [ ] ReturnedResults ; ReturnedResults = DataSet.Tables [ `` M... | NullReferenceException error when searching database table for entries |
C# | I 'm trying to understand this RegEx statement in details . It 's supposed to validate filename from ASP.Net FileUpload control to allow only jpeg and gif files . It was designed by somebody else and I do not completely understand it . It works fine in Internet Explorer 7.0 but not in Firefox 3.6 . | < asp : RegularExpressionValidator id= '' FileUpLoadValidator '' runat= '' server '' ErrorMessage= '' Upload Jpegs and Gifs only . '' ValidationExpression= '' ^ ( ( [ a-zA-Z ] : ) | ( \\ { 2 } \w+ ) \ $ ? ) ( \\ ( \w [ \w ] . * ) ) ( .jpg|.JPG|.gif|.GIF ) $ '' ControlToValidate= '' LogoFileUpload '' > < /asp : RegularE... | Understand this RegEx statement |
C# | I want to split a border attribute from CSS into its constituent parts i.e : IntoI have split off the border : and semi-colon before this , so I simply need to parse the value section of the attributeNow in CSS you can have any combination of the 3 above attributes present soAll are legal so I need to account for that.... | .someClass { border : 1px solid black ; } border-width : 1pxborder-style : solid ; border-color : black ; border : 1px solid ; border : solid Gold ; border : 1em ; border : 1mm # 000000 ; border : 1px inset rgb ( 12 , 44 , 199 ) ; ( [ 0-9 ] + [ a-zA-Z| % ] + ) * * ( [ a-zA-Z ] * ) * ( . * ) | Regex for splitting CSS border attribute into its parts |
C# | I have a list of bugs MyBugList created using the following classI wanted to group these bugs based on State and Severity . I used the following code to achieve it.This linq query gives me output like the followingHowever I would like to get an output like belowIs it possible to get this via a LINQ query on MyBugList o... | internal class BugDetails { public int Id { get ; set ; } public string State { get ; set ; } public string Severity { get ; set ; } } var BugListGroup = ( from bug in MyBugList group bug by new { bug.State , bug.Severity } into grp select new { BugState = grp.Key.State , BugSeverity = grp.Key.Severity , BugCount = grp... | LINQ query on an object list to get distribution based on multiple fields |
C# | I have some doubts regarding the using statement : I have a class called MyJob which is Disposable . Then i also have a property on MyJob JobResults that is also Disposable.MY code : MY First question is : In this case after the using block are both MyJob and MyJob.Results disposed or only MyJob and NOT MyJob.Results ?... | using ( MyJob job = new MyJob ( ) ) { //do something . FormatResults ( job.JobResults ) } public string FormatResuls ( JobResuts results ) { } Tasks allTasks = List < Tasks > try { foreach ( Task t in allTasks ) { // Each tasks makes use of an IDisposable object . t.Start ( ) ; } Task.WaitAll ( allTasks ) ; } catch ( A... | using statement usage in C # |
C# | I was cleaning up some code and removed an if statement that was no longer necessary . However , I realized I forgot to remove the brackets . This of course is valid and just created a new local scope . Now this got me thinking . In all my years of C # development , I have never come across a reason to use them . In fa... | void SomeMethod ( ) { { int i = 20 ; } int i = 50 ; //Invalid due to i already being used above . } void SomeMethod2 ( ) { { int i = 20 ; } { int i = 50 ; //Valid due to scopes being unrelated . } { string i = `` ABCDEF '' ; } } | Explicit Local Scopes - Any True Benefit ? |
C# | I 'm trying to wrap my head around what the C # compiler does when I 'm chaining linq methods , particularly when chaining the same method multiple times.Simple example : Let 's say I 'm trying to filter a sequence of ints based on two conditions.The most obvious thing to do is something like this : But we could also c... | IEnumerable < int > Method1 ( IEnumerable < int > input ) { return input.Where ( i = > i % 3 == 0 & & i % 5 == 0 ) ; } IEnumerable < int > Method2 ( IEnumerable < int > input ) { return input.Where ( i = > i % 3 == 0 ) .Where ( i = > i % 5 == 0 ) ; } | Understanding how the C # compiler deals with chaining linq methods |
C# | Env : C # , VStudio 2013 , 4.5 Framework , WinformsGoal : Getting the number of files ( Count ) in a folder and subfolder that match extensions stored in an array of string . The array of extension can be with the `` . '' of not . { `` .dat '' , '' txt '' , '' .msg '' } What i 've done so far : When I 'm having the `` ... | string [ ] ext= new string [ ] { `` .txt '' , `` .msg '' , `` .dat '' } ; totalFilesInTN = Directory.EnumerateFiles ( dlg1.SelectedPath , `` * . * '' , SearchOption.AllDirectories ) .Count ( s = > ext.Any ( s1 = > s1 == Path.GetExtension ( s ) ) ) ; string [ ] ext= new string [ ] { `` txt '' , `` .msg '' , `` dat '' } ... | Count of files in C # with LINQ |
C# | Which way can I decide the computer has a wifi adapter ? When I test my code it works , but I am uncertain , will it always work ? | private bool hasWifi ( ) { try { WlanClient wlanclient = new WlanClient ( ) ; } catch ( System.ComponentModel.Win32Exception except ) { return false ; } return true ; } | How to determine if the computer has a wifi adapter ? |
C# | I 'm trying to set up CSP in an asp.net core webapp , and the CSP part works fine , I can see the violations in the browser console as they are sent to the report-uri endpoint.However , I can not seem to create the correct method in a controller to receive these messages ! I create a method in the controller as : and i... | [ HttpPost ] [ AllowAnonymous ] public IActionResult UriReport ( CspReportRequest request ) { _log.LogError ( `` CSP violation : `` + request ) ; return Ok ( ) ; } services.Configure < MvcOptions > ( options = > { options.InputFormatters.OfType < JsonInputFormatter > ( ) .First ( ) .SupportedMediaTypes.Add ( new MediaT... | csp-report endpoint in asp.net core |
C# | What is the proper XML-comment syntax to refer to the SingleOrDefault extension method on the IEnumerable interface ? My latest attempt is : The warning is : XML comment on 'yourMethod ' has cref attribute 'IEnumerable.SingleOrDefault ( ) ' that could not be resolved | < see cref= '' IEnumerable { T } .SingleOrDefault { T } ( ) '' / > | How to refer to an extension method of a generic class in XML comments |
C# | So I have the following block of code inside a method : ( all variables are local ) As you can see , the two try statements are different , but the two sets of catch statements are exactly the same . I 've been trying to think of a way that it might be possible to not repeat myself here , but I have n't really thought ... | // ... try { if ( postXml ! = null ) using ( StreamWriter writer = new StreamWriter ( req.GetRequestStream ( ) ) ) writer.Write ( postXml.ToString ( ) ) ; } catch ( WebException ex ) { HttpWebResponse response = ex.Response as HttpWebResponse ; if ( response ! = null ) result = HandleOtherResponse ( response , out stat... | DRY With Different Try Statements and Identical Catch Statements |
C# | Given an async method : And calling it through an intermediate method , should the intermediate method await the async method IntermediateA or merely return the Task IntermediateB ? As best I can tell with the debugger , both appear to work exactly the same , but it seems to me that IntermediateB should perform better ... | public async Task < int > InnerAsync ( ) { await Task.Delay ( 1000 ) ; return 123 ; } public async Task < int > IntermediateA ( ) { return await InnerAsync ( ) ; } private Task < int > IntermediateB ( ) { return InnerAsync ( ) ; } | Call chain for async/await ... await the awaitable or return the awaitable ? |
C# | I have seen code with the following logic in a few places : What is the point of setting foo to null in the dictionary before removing it ? I thought the garbage collection cares about the number of things pointing to whatever *foo originally was . If that 's the case , would n't setting myDictonary [ `` foo '' ] to nu... | public void func ( ) { _myDictonary [ `` foo '' ] = null ; _myDictionary.Remove ( `` foo '' ) ; } | Can someone explain what the point of nulling an object before it goes out of scope is ? |
C# | There is library A calling library B using a C # extension method.I got a weird error from the C # compiler : The type 'System.Windows.Forms.Control ' is defined in an assembly that is not referenced . You must add a reference to assembly 'System.Windows.Forms , Version=4.0.0.0None of the libraries A or B are dependent... | //static method syntax works finevar leads = SourceLeadConfigurationHelper.GetLeads ( enLeadSystem ) ; //extension method syntax cause error//error The type 'System.Windows.Forms.Control ' is defined in an assembly that is not referenced . var leads = enLeadSystem.GetLeads ( ) ; public static class SourceLeadConfigurat... | Extension method call does not compile , but static method call to same code does compile |
C# | Consider the following code : To my surprise , this outputs 47 ; in other words , the explicit operator long is called even though the cast is to decimal.Is there something in the C # spec that explicitly says that this should happen ( if so , where exactly ) or is this the result of some other rule ( s ) I ’ m missing... | class Program { public static explicit operator long ( Program x ) { return 47 ; } static int Main ( string [ ] args ) { var x = new Program ( ) ; Console.WriteLine ( ( decimal ) x ) ; } } | Why does an explicit cast to ‘ decimal ’ call an explicit operator to ‘ long ’ ? |
C# | I have this XAML : Is there some way to shift that unicode character & # x24D8 ; into a shared resource ( like a constant or a StaticResource ) ? What I have triedMethod 1This works fine , but it requires a valid binding to work : And in code behind : Method 2This method seems like it might work , but no luck : | < TextBlock Text= '' Message with unicode char : & # x24D8 ; '' / > < Grid > < Grid.Resources > < system : String x : Key= '' ToolTipChar '' > { 0 } & # x24D8 ; < /system : String > < /Grid.Resources > < TextBlock Text= '' { Binding MyText , StringFormat= { StaticResource ToolTipChar } } '' / > < /Grid > public string ... | WPF : How to shift Unicode character into a shared resource ? |
C# | The grid in WPF currently has a grid system like this : Is there a way to make it behave like this : Ideally I would like the RowSpan to extend an item upwards instead of downwards . Example : My datasource stores a cube on the map as 0,0 with the intent of it being displayed on the bottom left corner . However the gri... | Cols + + + + + | 0 | 1 | 2 | 3 | + -- + -- -| -- -| -- -| -- -| -- - 0 | | | | |+ -- + -- -| -- -| -- -| -- -| -- - Rows 1 | | | | | + -- + -- -| -- -| -- -| -- -| -- - 2 | | | | | + -- + -- -| -- -| -- -| -- -| -- - Cols + + + + + | 0 | 1 | 2 | 3 | + -- + -- -| -- -| -- -| -- -| -- - 2 | | | | |+ -- + -- -| -- -| -- -... | Change Grid Coordinate System |
C# | I have been trying to draw equilateral triangles on the sides of a larger triangle . The first triangle is drawn by a separate method setting points A , B and C. So far I have just started with two sides , I am able to find the first two points of the smaller triangles , but I am unable to determine the correct formula... | float a =0 ; Point p = new Point ( pnlDisplay.Width / 2 - ( pnlDisplay.Width / 2 ) /3 , 200 ) ; Triangle t = new Triangle ( p , pnlDisplay.Width / 3 , 0 ) ; drawEqTriangle ( e , t ) ; Point p1 = new Point ( ) ; Point p2 = new Point ( ) ; Point p3 = new Point ( ) ; p1.X = Convert.ToInt32 ( A.X + t.size / 3 ) ; p1.Y = Co... | C # Drawing equilateral triangles on the sides of another equilateral triangle |
C# | Possible Duplicate : Define a generic that implements the + operator I am recently working on a C # class library implementing an algorithm . The point is that I would like the users of the library to be able to choose the machine precision ( single or double ) the algorithm should operate with , and I 'm trying to do ... | Algorithm < double > a = new Algorithm < double > ( ) ; /** Some initializations here */ double result = a.Solve ( ) ; Algorithm < float > a = new Algorithm < float > ( ) ; /** Some initializations here */ float result = a.Solve ( ) ; | How to impose , in a C # generic type parameter , that some operators are supported ? |
C# | I can type In fact , I expect I could keep going adding dimensions to Int.MaxValue though I have no idea how much memory that would require.How could I implement this variable indexing feature in my own class ? I want to encapsulate a multi dimensional array of unknown dimensions and make it available as a property thu... | Square [ , , , ] squares = new Square [ 3 , 2 , 5 , 5 ] ; squares [ 0 , 0 , 0 , 1 ] = new Square ( ) ; class ArrayExt < T > { public Array Array { get ; set ; } public T this [ params int [ ] indices ] { get { return ( T ) Array.GetValue ( indices ) ; } set { Array.SetValue ( value , indices ) ; } } } ArrayExt < Square... | How to implement Array indexer in C # |
C# | I am trying the code to find out whether the user has already signed in or not ? Even if the user has already logged in , it returns Unknown . What is the problem with this ? | LiveAuthClient LCAuth = new LiveAuthClient ( ) ; LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync ( ) ; | LiveLoginResult.Status is Unknown ? |
C# | How would I convert this to HttpClient ? What I 'm looking to do is submit a Tweet to the Twitter api and get the response as Json . The HttpWebRequest is working fine but I just want to port it to HttpClient . I made an attempt at it in the second code example , but it 's not actually sending or receiving the response... | HttpWebRequest request = null ; WebResponse response = null ; string responseCode = String.Empty ; try { string postBody = `` status= '' + EncodingUtils.UrlEncode ( status ) ; request = ( HttpWebRequest ) HttpWebRequest.Create ( resource_url ) ; request.ServicePoint.Expect100Continue = true ; request.UseDefaultCredenti... | Refactor HttpWebRequest to HttpClient ? |
C# | I 'm receiving several bit fields from hardware.My code was originally : Then I remembered the flags enum and am considering changing it to : and so on.Which is best practice and what if any are the pros and cons of each approach ? EDIT : I 'm interested to know if there are any practical differences between the two ap... | public readonly byte LowByte ; public bool Timer { get { return ( LowByte & 1 ) == 1 ; } } [ Flags ] public enum LowByteReasonValues : byte { Timer = 1 , DistanceTravelledExceeded = 2 , Polled = 4 , GeofenceEvent = 8 , PanicSwitchActivated = 16 , ExternalInputEvent = 32 , JourneyStart = 64 , JourneyStop = 128 } public ... | What are the pros and cons of using a flags enum ? |
C# | Take a look at the code : I want to remove all whitespace from the original string and then get the individual characters.The result surprized me.The variable exprCharsNoWhitespace contains , as expected , no whitespace , but unexpectedly , only almost all of the other characters . The last occurence of ' & ' is missin... | string expression = `` x & ~y - > ( s + t ) & z '' ; var exprCharsNoWhitespace = expression.Except ( new [ ] { ' ' , '\t ' } ) .ToList ( ) ; var exprCharsNoWhitespace_2 = expression.Replace ( `` `` , `` '' ) .Replace ( `` \t '' , `` '' ) .ToList ( ) ; // output for examinationConsole.WriteLine ( exprCharsNoWhitespace.A... | Why is one character missing in the query result ? |
C# | I used to be a C++ programer on Windows.I know that the compiler will optimizes the ternary operator in C++.C++ code : Because of the pipeline stuff , the generated native code is shown as below ( of course Release model ) : C # code : I looked up the native code JIT generated , but there is no optimization at all ( st... | # include `` stdafx.h '' int _tmain ( int argc , _TCHAR* argv [ ] ) { int result = argc > 3 ? 1 : 5 ; printf ( `` % d '' , result ) ; return 0 ; } int result = argc > 3 ? 1 : 5 ; 00B21003 xor eax , eax 00B21005 cmp dword ptr [ argc ] ,300B21009 setle al 00B2100C lea eax , [ eax*4+1 ] namespace TernaryOperatorCSharp { s... | C # vs C++ ternary operator |
C# | I 've struggled a lot with how to show a modal panel on click on a button inside a grid view.To context : I have a data row with a string field that can contain a simple text or a base 64 encoded image , so I 'm using a custom template to define when to show the raw content or a button `` View Image '' . This image wil... | < asp : Panel ID= '' pnlModalOverlay '' runat= '' server '' Visible= '' true '' CssClass= '' Overlay '' > < asp : Panel ID= '' pnlModalMainContent '' runat= '' server '' Visible= '' true '' CssClass= '' ModalWindow '' > < div class= '' WindowTitle '' > < asp : Label ID= '' lbTitle '' runat= '' server '' / > < /div > < ... | Modal Panel Doesn ’ t Appear When Called by Button Inside a Grid View ’ s Cell |
C# | I have the following structureOn the code behind I get the repeater ItemDataBound event , get the control using var button1 = e.Item.FindControl ( `` Button1 '' ) as LinkButton ; then I assign a CommandArgument with the ID of the current element.This is being executed immediately after the CreateChildControls method.Th... | < asp : UpdatePanel ID= '' MyUpdatePanel '' runat= '' server '' > < ContentTemplate > < asp : MultiView ID= '' MyViews '' runat= '' server '' > < asp : View ID= '' List '' runat= '' server '' > < asp : Repeater runat= '' server '' ID= '' Repeater1 '' > < ItemTemplate > < asp : LinkButton ID= '' Button1 '' runat= '' ser... | How to change a View with a button on a Repeater ? |
C# | ContextWe have a C # program , that deals with time.We have clients in France , so we convert times to and from France 's timezone.In our C # code : we use Central European Standard Time as a time zone for France.It describes a timezone , which follows DST changes : on the last sunday of march ( 3 AM ) , clocks swicth ... | using System ; using System.Globalization ; namespace TestingApp { class Program { static void Main ( string [ ] args ) { var tz = TimeZoneInfo.FindSystemTimeZoneById ( `` Central European Standard Time '' ) ; string [ ] times = { // In 1995 : // last sunday in september was sept. 24th // last sunday in october was oct... | What timezone should I use for France to support old and new daylight saving adjustments ? |
C# | In C # when an Task or Task < T > method is returned from within a using statement is there any risk of the cleanup not properly occurring , or is this a poor practice ? What concerns are there as it pertains to the closure of the variable in the using block ? Consider the following : In the example above the asynchron... | public Task < string > GetAsync ( string url ) { using ( var client = new HttpClient ( ) ) { return client.GetStringAsync ( url ) ; } } public async Task < string > GetAsync ( string url ) { string response = string.Empty ; using ( var client = new HttpClient ( ) ) { response = await client.GetStringAsync ( url ) ; } r... | C # Task returning method in using block |
C# | I ’ m writing console application which does some work by scheduler and write output to console . Everything is good but when I click on the console it stops working and waits for my right click . After that it continues working.I thought that it simply doesn ’ t write text to console and does what it needs to do but n... | static void Main ( string [ ] args ) { Console.WriteLine ( `` Started ... '' ) ; var timer = new System.Timers.Timer ( 1000 ) ; timer.Elapsed += timer_Elapsed ; timer.Start ( ) ; Console.ReadLine ( ) ; } static void timer_Elapsed ( object sender , ElapsedEventArgs e ) { Console.WriteLine ( `` Writing to file `` + DateT... | Console application ( C # ) is stuck while interaction |
C# | Is there a way to put the GC on hold completely for a section of code ? The only thing I 've found in other similar questions is GC.TryStartNoGCRegion but it is limited to the amount of memory you specify which itself is limited to the size of an ephemeral segment.Is there a way to bypass that completely and tell .NET ... | var items = XElement.Load ( `` myfile.xml '' ) .Element ( `` a '' ) .Elements ( `` b '' ) // There are about 2 to 5 million instances of `` b '' .Select ( pt = > new { aa = pt.Element ( `` aa '' ) , ab = pt.Element ( `` ab '' ) , ac = pt.Element ( `` ac '' ) , ad = pt.Element ( `` ad '' ) , ae = pt.Element ( `` ae '' )... | Put GC on hold during a section of code |
C# | We have entity framework implemented in our Web API 2.0 code . To call database entities , we are using store procedure calls . Our entire application is hosted in Microsoft Azure cloud . Here are the two exception which we are facing.Message : An error occurred while executing the command definition . See the inner ex... | < add name= '' *****Entities '' connectionString= '' metadata=res : //*/Models.Database.*****.csdl|res : //*/Models.Database.*****.ssdl|res : //*/Models.Database . *****.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source=***** ; Failover Partner=***** ; initial catalog=***** ; user ... | SQL Connection Errors in Microsoft Azure |
C# | How can I bind a control inside a usercontrol resource to a property ? Alternatively , can I find the control from the code behind and get & set the value from there ? Here is my markup . I 've stripped it down to just the relevant part : Salesmen.xaml : And here 's my property . Despite the two-way binding it is alway... | < UserControl.Resources > < ControlTemplate x : Key= '' EditAppointmentTemplate1 '' TargetType= '' local : SchedulerDialog '' x : Name= '' ControlTemplate '' > < ScrollViewer HorizontalScrollBarVisibility= '' Auto '' VerticalScrollBarVisibility= '' Auto '' > < Grid > < Grid Name= '' grdTotal '' Grid.Row= '' 4 '' Visibi... | How can I bind or otherwise get & set a value of a control in a resource ? |
C# | I have defined the following classes and methods : This compiles fine . Woo hoo ! Half-way there . Then , I try to use it later with code like this : This , however , dies with the following error message The type ToolStripStatusLabel can not be used as type parameter C in the generic type or method Something < T > .Do... | using System ; using System.Linq.Expressions ; using System.Windows.Forms ; public class ReturnValue < T , S > { } public class Something < T > { // Sorry about the odd formatting . Trying to get it to fit nicely ... public ReturnValue < T , C > Do < C , S > ( C control , Expression < Func < C , S > > controlProperty )... | Why Does C # Not Bind Correctly to Generic Overridden Methods ? |
C# | is evaluated to 108 . Why ? IMO the ( int ) -cast should be evaluated after the multiplication . | ( int ) ( ( float ) 10.9 * 10 ) | Understanding the given calculation ( cast + multiplication ) |
C# | I 'm writing a program that writes C # that eventually gets compiled into an application . I would like each of the generated types to provide a `` deep clone '' function which copies the entire tree of data . That is , I want someone to be able to do : instead ofHowever , C # does n't allow you to do this in a simple ... | var x = new Base ( ) ; // Base has public virtual Base DeepClone ( ) { ... } var y = new Derived ( ) ; // Derived overrides DeepCloneBase a = x.DeepClone ( ) ; Base b = y.DeepClone ( ) ; // Derived c = x.DeepClone ( ) ; // Should not compileDerived d = y.DeepClone ( ) ; // Does not compile , DeepClone returns Base var ... | Is it possible to implement the `` virtual constructor '' pattern in C # without casts ? |
C# | I 'm trying to update a project which makes heavy use of comparison against SyntaxToken.Kind . This property appears to have disappeared in newer versions of Roslyn and I wondered if there an alternative method or an extension method I could write to get the same functionality ? The code has many references such as : A... | if ( expression.OperatorToken.Kind == SyntaxKind.PlusEqualsToken ) | How to get the SyntaxToken.Kind in current version of Roslyn ? |
C# | I am still new to overloading operators . I thought i was doing a great job until i hit this problem . NullReferenceException is thrown on the ! = operator . I assume its using it in the CompareTo method but i 'm not totally sure . If anyone can point me in the right direction i would be very grateful.When i comment ou... | using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; List < Tas... | How to properly override equality ? |
C# | Consider the following class : This is what the compiler generates ( in a slightly less readable way ) : This way the delegate passed with the first call is initialized once and reused on multiple Test calls.However , the expression tree passed with the second call is not reused - a new lambda expression is initialized... | class Program { static void Test ( ) { TestDelegate < string , int > ( s = > s.Length ) ; TestExpressionTree < string , int > ( s = > s.Length ) ; } static void TestDelegate < T1 , T2 > ( Func < T1 , T2 > del ) { /* ... */ } static void TestExpressionTree < T1 , T2 > ( Expression < Func < T1 , T2 > > exp ) { /* ... */ ... | Why do n't non-capturing expression trees that are initialized using lambda expressions get cached ? |
C# | I am working on a library of COM Add-in and Excel Automation Add-in , whose core codes are written in C # . I 'd like to set an optional argument for the function and I know that this is legal for both C # and VBA , and even Excel WorksheetFunction . But I find that finally the optional argument works exclusively for C... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Xml.Linq ; using Excel = Microsoft.Office.Interop.Excel ; using Office = Microsoft.Office.Core ; using Microsoft.Office.Tools.Excel ; namespace TestVBA { public partial class ThisAddIn { private void ThisAddIn_Startup... | Optional Argument of COM Add-in vs Automation Add-in Written in C # |
C# | Possible Duplicates : confused with the scope in c # C # Variable Scoping I am curious about the design considerations behind the scope of variables which are declared in the initialization part of for-loops ( etc ) . Such variables neither seem to be in-scope or out-of scope or am I missing something ? Why is this and... | for ( int i = 0 ; i < 10 ; i++ ) { } i = 12 ; //CS0103 : The name ' i ' does not exist in the current contextint i = 13 ; //CS0136 : A local variable named ' i ' can not be declared in this scope //because it would give a different meaning to ' i ' , which is already //used in a 'child ' scope to denote something else | C # : Definition of the scope of variables declared in the initialization part of for-loops ? |
C# | For a project I 'm busy with the Google Adwords api ( client library = C # ) . I show the visitor an estimate of traffic based on keywords and locality/city currently . It 's using following methodhttps : //developers.google.com/adwords/api/docs/guides/traffic-estimator-serviceI want to add an extra requirement : the e... | var proximity = new Proximity { radiusDistanceUnits = ProximityDistanceUnits.KILOMETERS , radiusInUnits = seaConfigurationModel.Proximity , geoPoint = new GeoPoint ( ) { latitudeInMicroDegrees = 43633941 , longitudeInMicroDegrees = -79398718 } } ; campaignEstimateRequest.criteria = new Criterion [ ] { languageCriterion... | How add a radius / proximity around a city for estimating traffic ( Google Adwords ) ? |
C# | I 'm trying to create a simple program with MonoGame in Xamarin Studio 4.0.10 ( build 5 ) .But when I try to load some textures using Content.Load method , I receive an exception System.MissingMethodException with a message The actual lines of code I am using are : I did some googling and found out that this happens be... | Method not found : 'MonoMac.AppKit.NSImage.AsCGImage ' . protected override void LoadContent ( ) { //some stuff here Texture2D freezeTexts = new Texture2D [ 5 ] ; for ( int i = 0 ; i < 5 ; i++ ) { freezeTexts [ i ] = Content.Load < Texture2D > ( `` freeze '' +i ) ; // exception here } //some other stuff here } | How to fix MissingMethodException during Content.Load < Texture2D > in Xamarin Studio on MacOS X ? |
C# | I have a class project a.dll which is compiled in C # . It contains the following code.from a C # project I can call these functions like thisBut how can I call this from a VB.Net Project ? I am not in a position to use Visual Studio right now . So its very helpful if someone will provide an answer.EDIT 1I am having a ... | public class MyClass { public int Add ( int i , int j ) { return ( i+j ) ; } public int add ( int i , int j ) { return ( i+j ) *2 ; } } public class MyOtherClass { MyClass mcls=new MyClass ( ) ; mcls.Add ( 1,2 ) ; mcls.add ( 2.3 ) ; } Dim myObj as New MyClassmyObj.Add ( 1,2 ) myObj.add ( 1,2 ) | How to call a function defined in C # with same params , return type and same name but in different case from a VB.NET project |
C# | After Windows has updated , some calculated values have changed in the last digit , e.g . from -0.0776529085243926 to -0.0776529085243925 . The change is always down by one and both even and odd numbers are affected . This seems to be related to KB4486153 , as reverting this update changes the values back to the previo... | var output = -0.07765290852439255 ; Trace.WriteLine ( output ) ; // This printout changes with the update.var dictionary = new Dictionary < int , double > ( ) ; dictionary [ 0 ] = output ; // Hover over dictionary to see the change in debug mode output [ date ] = input [ date ] / input [ previousDate ] - 1 ; { [ 2011-0... | Rounding of last digit changes after Windows .NET update |
C# | This is for Project Euler , problem 8.I am trying to foreach through the array of numbers , each time skipping the last number and pulling the next 13 adjacent numbers in the array.My code : The problem I 'm running into is , every time it enumerates through the array , it subtracts the amount that x is , from how many... | for ( int x = 0 ; x < 987 ; x++ ) { foreach ( int number in numbers.Take ( 13 ) .Skip ( x ) ) { hold = hold * number ; adjacent [ index ] = number ; index++ ; } if ( hold > product ) { product = hold ; } Array.Clear ( adjacent , 0 , adjacent.Length ) ; index = 0 ; hold = 1 ; } | array.Take ( 13 ) .Skip ( x ) is subtracting the take |
C# | We have a WEB API project that recently was moved to a new server . I 'm running my project after making some additions to its ' payload , but it suddenly throws the following error : Unable to cast object of type 'System.Net.Http.Formatting.JsonContractResolver ' to type 'Newtonsoft.Json.Serialization.DefaultContractR... | protected void Application_Start ( ) { GlobalConfiguration.Configure ( WebApiConfig.Register ) ; var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings ; var contractResolver = ( DefaultContractResolver ) serializerSettings.ContractResolver ; contractResolver.IgnoreSerial... | `` Unable to cast object of type 'System.Net.Http.Formatting.JsonContractResolver ' to type 'Newtonsoft.Json.Serialization.DefaultContractResolver ' . '' |
C# | I have an object o that is known to be a boxed int or uint : I do n't know what 's in the box , all I care about is that there 's 4 bytes in there that I want to coerce to an int or uint . This works fine in an unchecked context when I have values ( instead of boxes ) : Note : By default everything in C # is unchecked ... | object o = int.MinValueobject o = ( uint ) int.MinValue // same bytes as above unchecked { int a = ( int ) 0x80000000u ; // will be int.MinValue , the literal is a uint uint b = ( uint ) int.MinValue ; } | Unboxing uint/int without knowing what 's inside the box |
C# | I an having Two Lists . I want to get the matched and unmatched values based on ID and add the results to another List . I can get both of these using Intersect/Except . But I can get only ID in the resultant variables ( matches and unmatches ) . I need all the properties in the Template . | List < Template > listForTemplate = new List < Template > ( ) ; List < Template1 > listForTemplate1 = new List < Template1 > ( ) ; var matches = listForTemplate .Select ( f = > f.ID ) .Intersect ( listForTemplate1 .Select ( b = > b.ID ) ) ; var ummatches = listForTemplate .Select ( f = > f.ID ) .Except ( listForTemplat... | How to copy a List < > to another List < > with Comparsion in c # |
C# | I wanted to mock an entityframwork DbSet using Foq . It goes something like : I tried coercing and casting x to an IQueryable at some places but that does n't work.As you can see here in the docs for DbSet it does implement the IQueryable interface via DbQuery , but does so by `` explicitly '' implementing the properti... | let patients = ( [ Patient ( Guid `` 00000000-0000-0000-0000-000000000001 '' ) ; Patient ( Guid `` 00000000-0000-0000-0000-000000000002 '' ) ; Patient ( Guid `` 00000000-0000-0000-0000-000000000003 '' ) ; ] ) .AsQueryable ( ) let mockPatSet = Mock < DbSet < Patient > > .With ( fun x - > < @ // This is where things wron... | Mocking a class with an explicitly implemented interface using Foq |
C# | I have these extension methods and enum type : The first if below compiles ; the second does not : They only vary by the extra set of parentheses . Why do I have to do this ? At first I suspected it was doing a double implicit cast from bool ? to bool and then back to bool ? , but when I remove the first extension meth... | public static bool IsOneOf < T > ( this T thing , params T [ ] things ) { return things.Contains ( thing ) ; } public static bool IsOneOf < T > ( this T ? thing , params T [ ] things ) where T : struct { return thing.HasValue & & things.Contains ( thing.Value ) ; } public enum Color { Red , Green , Blue } if ( ( x.Y ? ... | Why do I have to place ( ) around null-conditional expression to use the correct method overload ? |
C# | I 've normally been creating Prism Events used by the EventAggregator like : public class SomeEvent : CompositePresentationEvent < SomeEventArgs > { } But while looking at a co-workers code I noticed they did : I guess my first question is why does this even compile ? It seems to me that it 's implementing a class that... | public class SomeEventArgs { public string Name { get ; set ; } } public class SomeEvent : CompositePresentationEvent < SomeEvent > { public string Name { get ; set ; } } | Define class with itself as generic implementation . Why/how does this work ? |
C# | I am trying to clear all items from a ToolStripDropDownButton.Since they are disposable , I call the dispose method on each of them.But I see that after calling the dispose ( ) method , the IsDisposed property still returns false.Why is that and how can I check if Dispose ( ) is called on any object ? It is not a probl... | private void ClearDropDownAccessConnections ( ) { ToolStripItem button = null ; for ( int i = toolStripDropDownButtonAccess.DropDownItems.Count - 1 ; i > 0 ; i -- ) { button = toolStripDropDownButtonAccess.DropDownItems [ i ] as ToolStripItem ; if ( ( button.Tag ! = null ) & & ( ( int ) button.Tag == 10 ) ) { toolStrip... | Why does IsDisposed return false after calling Dispose ( ) ? |
C# | I am college student ( computer science ) and have just started a C # programming class.For our assignments I have been using a class called `` Display '' where I put any console output that could be used several times throughout a project . For example , a request to continue or exit program . Instead of typing it out... | namespace Chapter_6_10 { class Program { static void Main ( ) { string triangle = `` '' , result = `` `` ; ; char printingCharacter = ' ' ; int peakNumber = 0 ; Display.Instructions ( ) ; Display.Continue ( ) ; // perform a do ... while loop to build triangle up to peak do { Console.Clear ( ) ; Request.UserInput ( out ... | correct use of classes ? |
C# | I 'm downloading an Excel file ( dynamically created in a Winforms app and saved to a database ) in a Web API project using this method : This works just fine ( except that there is no downloading action visible , such as the file 's icon dropping to the taskbar , as is normally the case when downloading files from the... | [ Route ( `` api/deliveryperformance/ { unit } / { begindate } / { enddate } '' ) ] public HttpResponseMessage Get ( string unit , string begindate , string enddate ) { // adapted the first part of this code from http : //stackoverflow.com/questions/11176066/how-do-i-insert-retrieve-excel-files-to-varbinarymax-column-i... | How can I download a file to a remote machine the same or similarly to how I 'm doing it to my own machine ? |
C# | how can i optimized this code ? i dont like to have case statement , is there a way i can improve this code ? | protected void ddlFilterResultBy_SelectedIndexChanged ( object sender , EventArgs e ) { string selVal = ddlFilterResultBy.SelectedValue.ToString ( ) .ToLower ( ) ; switch ( selVal ) { case `` date '' : pnlDate.Visible = true ; pnlSubject.Visible = false ; pnlofficer.Visible = false ; pnlCIA.Visible = false ; pnlMedia.V... | how can i make this code more optimized |
C# | What would be the best way to override the GetHashCode function for the case , whenmy objects are considered equal if there is at least ONE field match in them.In the case of generic Equals method the example might look like this : Still , I 'm confused about making a good GetHashCode implementation for this case.How s... | public bool Equals ( Whatever other ) { if ( ReferenceEquals ( null , other ) ) return false ; if ( ReferenceEquals ( this , other ) ) return true ; // Considering that the values ca n't be 'null ' here . return other.Id.Equals ( Id ) || Equals ( other.Money , Money ) || Equals ( other.Code , Code ) ; } | C # GetHashCode question |
C# | With Moq , it is possible to verify that a method is never called with certain arguments ( that is , arguments satisfying certain predicates ) using Times.Never.But how to verify that , no mater how many times a method is called , it is always called with certain arguments ? The default appears to be Times.AtLeastOnce.... | should_only_write_valid_xml_documentsMock.Get ( this.writer ) .Verify ( w = > w.Write ( It.Is < XDocument > ( doc = > XsdValidator.IsValid ( doc ) ) , It.Is < int > ( n = > n < 3 ) ) , Times.Always ) ; | Why is n't there a Times.Always in Moq ? |
C# | I thought it would be a good idea to use CancellationToken in my controller like so : The issue is that now Azure Application Insights shows a bunch of exceptions of type System.Threading.Tasks.TaskCancelledException : A Task was canceled . as well as the occasional Npgsql.PostgresException : 57014 : canceling statemen... | [ HttpGet ( `` things '' , Name = `` GetSomething '' ) ] public async Task < ActionResult > GetSomethingAsync ( CancellationToken ct ) { var result = await someSvc.LoadSomethingAsync ( ct ) ; return Ok ( result ) ; } app.Use ( async ( ctx , next ) = > { try { await next ( ) ; } catch ( Exception ex ) { if ( ctx.Request... | Stop Exception generated by CancellationToken from getting Reported by ApplicationInsights |
C# | I 've just started with AutoMapper in C # . I 've succesfully created a mapping like this : I 've also found a way to add some logic to specific properties , like formatting a date ( in InputTypeA ) to a string in a specific format ( in OutputTypeA ) .Now I need to do the same for a number of float properties , but I '... | Mapper.CreateMap < InputTypeA , OutputTypeA > ( ) .ForMember ( dest = > dest.MyDateProperty , opt = > opt.ResolveUsing ( src = > String.Format ( `` { 0 : yyyy-MM-dd } '' , src.MyDateProperty ) ) ) ; Mapper.CreateMap < float , string > ( ) .ConvertUsing ( src = > String.Format ( CultureInfo.InvariantCulture.NumberFormat... | Special treatment for float properties in some but not all AutoMapper mappings |
C# | Earlier today , as I was coding a method and it struck me that I was n't sure exactly why the idiom I was implementing compiles . If everything else is abstracted away , it would look something like this : You have an explicitly infinite loop , and some set of conditions inside the loop that cause the loop to end with ... | private int Example ( ) { while ( true ) { if ( some condition ) { return 1 ; } } } private int Example2 ( ) { if ( true ) return 1 ; } private int Example3 ( ) { while ( true ) { if ( false ) { return 1 ; } } } | Are explicitly Infinite Loops handled in .NET as a special case ? |
C# | I know that multiple objects of same type can be used inside a using clause.Cant i use different types of objects inside the using clause ? Well i tried but although they were different names and different objects , they acted the same = had the same set of methodsIs there any other way to use the using class with diff... | using ( Font font3 = new Font ( `` Arial '' , 10.0f ) , font4 = new Font ( `` Arial '' , 10.0f ) ) { // Use font3 and font4 . } | Can i have different type of objects in a C # *using* block ? |
C# | What 's the easiest/straight-forward way of setting a default value for a C # public property ? // how do I set a default for this ? Please do n't suggest that I use a private property & implement the get/set public properties . Trying to keep this concise , and do n't want to get into an argument about why that 's so ... | public string MyProperty { get ; set ; } | C # Automatic Properties -- setting defaults |
C# | When I am invoking a number of methods to a Dispatcher , say the Dispatcher of the UI Thread , like herewill those methods be executed in the same order as I have invoked them ? | uiDispatcher.BeginInvoke ( new Action ( insert_ ) , DispatcherPriority.Normal ) ; uiDispatcher.BeginInvoke ( new Action ( add_ ) , DispatcherPriority.Normal ) ; uiDispatcher.BeginInvoke ( new Action ( insert_ ) , DispatcherPriority.Normal ) ; | Execution order of asynchronously invoked methods |
C# | The definition System.Linq.ILookUp readsSince IEnumerable is covariant in IGrouping < TKey , TElement > , IGrouping < TKey , TElement > is covariant in TElement and the interface only exposes TElement as a return type , I would assume that ILookup is also covariant in TElement . Indeed , the definitioncompiles without ... | interface ILookup < TKey , TElement > : IEnumerable < IGrouping < TKey , TElement > > , IEnumerable { int Count { get ; } IEnumerable < TElement > this [ TKey key ] { get ; } bool Contains ( TKey key ) ; } interface IMyLookup < TKey , out TElement > : IEnumerable < IGrouping < TKey , TElement > > , IEnumerable { int Co... | Should n't ILookup < TKey , TElement > be ( declared ) covariant in TElement ? |
C# | I have a problem where I want a group type to be strongly typed but if I do it does n't group correctly . See the code below ... The output : I would expect the result to be the same regardless of using an explicit type nor not i.e . should only be one group with 3 items not 3 groups with 1 item . What is going on here... | using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication35 { class Program { static void Main ( string [ ] args ) { List < Foo > foos = new List < Foo > ( ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) ... | Why does using anonymous type work and using an explicit type not in a GroupBy ? |
C# | I have used the three fields in the program and got the difference in usage but I am little confused where does these fields are getting stored ? either in data segment ( stack or heap ? ) or code segment ? in ILDASM the the fields are described as the followingfor static : .field private static int32 afor constant : .... | static int a ; const int b=1235 ; readonly int c ; | Where does the memory is allocated for static , constant and readonly fields ? |
C# | Using WindowsForms technology , I 'm trying to copy a file that is locally stored on the hard drive ( C : \ ) to a folder stored on a connected smartphone device via USB.The folder `` path '' is represented using friendly names as MyPCName\MyName\Card\Android in the Explorer navigation bar , and as : : { 20D04FE0-3AEA-... | Dim dirPath As String = `` : : { 20D04FE0-3AEA-1069-A2D8-08002B30309D } \\\ ? \usb # vid_04e8 & pid_6860 & ms_comp_mtp & samsung_android # 6 & 612ff8b & 1 & 0000 # { 6ac27878-a6fa-4155-ba85-f98f491d4f33 } \SID- { 20002 , SECZ9519043CHOHB01,31426543616 } \ { 01A00139-011B-0124-3301-29011C013501 } '' NativeMethods.CopyFi... | Which Win32 function must I use to copy a file to a smartphone folder ? |
C# | C # 5.0 Language Specification 7.6.10.2 Object initializers states that A member initializer that specifies an object initializer after the equals sign is a nested object initializer , i.e . an initialization of an embedded object . Instead of assigning a new value to the field or property , the assignments in the nest... | using System ; namespace ObjectCollectionInitializerExample { struct MemberStruct { public int field1 ; public double field2 ; } class ContainingClass { int field ; MemberStruct ms ; public int Field { get { return field ; } set { field = value ; } } public MemberStruct MS { get { return ms ; } set { ms = value ; } } }... | C # nested object initializer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.