lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | In the above code sample I create a circle and let it move around by pressing arrow keys . The state variable in question is the position of the circle , represented by a Vector2f object ( part of the SFML library ) My question relates to the end of the code segment , where I find the pressed key and then move the circ... | open SFML.Graphicsopen SFML.Windowlet window = new RenderWindow ( new VideoMode ( 200u , 200u ) , `` SFML works ! `` ) let shape = new CircleShape ( 10.0f , FillColor=Color.Green ) let mutable pressedKey = Keyboard.Key.Unknownlet moveKeys = [ Keyboard.Key.Up ; Keyboard.Key.Left ; Keyboard.Key.Down ; Keyboard.Key.Right ... | F # game development : Modifying state variables |
C# | Consider the following methods in C # : Let 's look at the instructions generated by the compiler : For the Decimal method : For the Int64 method : For the DateTime method : Why is the DateTime.GetHashCode ( ) method being treated as a virtual call of Object.GetHashCode ( ) , considering there is an overridden GetHashC... | public static int HashCodeFunction ( Decimal value ) { return value.GetHashCode ( ) ; } public static int HashCodeFunction ( Int64 value ) { return value.GetHashCode ( ) ; } public static int HashCodeFunction ( DateTime value ) { return value.GetHashCode ( ) ; } ldarga.s Parameter : System.Decimal valuecall Method : Sy... | Why is GetHashCode ( ) method compiled differently for DateTime compared to other structs ? |
C# | I just created a simple project with if statements to check if the statement is true , but then I stumbled into something weird.This is my sample codenope , you read that right . And I typed that right also . I have left out the else statement , but I have created curly brackets for it . When I compile , it runs fine .... | if ( x ==1 ) { do something ; } else if ( x==2 ) { do something ; } else if ( x==3 ) { do something ; } else if ( x==4 ) { do something ; } { do something ; } | Some Visual Studio 2010 or C # bug ? Or am I just dreaming ? |
C# | I want to do something but not sure how to describe it . I have this classBut I want to be able to do thiswhich should implicitly call GetPersonByName ( `` John '' ) .Is that possible ? What do I need to add to the Company class ? Thanks in advance ! | public class Company { private List < Person > _persons ; private Person GetPersonByName ( string name ) { // My code to select Person is here , which is fine } } Company c ; Person p = c.Persons [ `` John '' ] ; | C # - MyClass.MyProperty [ something ] |
C# | Currently I have this : However , I want this attribute to decorate only the setter , not the getter . Is there a way to do that ? | [ SomeCustomAttribute ] public string Name { get ; set ; } | Can an Attribute be set only on the Setter of an Auto-Implemented Property ? |
C# | QUESTION IS : If this issue is clear to you , please explain to me what im not seeing . My question is : How does ternary actually work ? To clarify my question : What does right to left associativity really mean here ? Why is associativity not the same as order of evaluation ? It is clearly like an if else statement .... | true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7evaluated as ; true ? false ? false ? ( false ? 3 : 4 ) : 5 : 6 : 7which evaluated as ; true ? false ? false ? 4 : 5 : 6 : 7which evaluated as ; true ? false ? ( false ? 4 : 5 ) : 6 : 7which evaluated as ; true ? false ? 5 : 6 : 7which evaluated as ; true ? ( false ? 5 : ... | Ternary operator as both left operative and right operative.. or neither |
C# | Other than testability , what 's the big advantage of utilizing D.I . ( and I 'm not talking about a D.I . framework or IoC ) over static classes ? Particularly for an application where you know a service wo n't be swapped out.In one of our c # application , our team is utilizing Dependency Injection in the web web GUI... | CreditEntity creditObj = CreditEntityManager.GetCredit ( customerId ) ; Decimal creditScore = CreditEntityManager.CalculateScore ( creditObj ) ; return creditScore ; //not shown , _creditService instantiation/injection in c-torsCreditEntity creditObj = _creditService.GetCredit ( customerId ) ; Decimal creditScore = _cr... | Other than testing , how is Dependency Injection any better than static classes/methods ? |
C# | C # , using VS2010 and I 've got something that makes no sense.At startup my program needs to load several hundred k from text files . After ensuring the loading code was working fine I threw it in a background thread . So long as this is run from within the IDE everything 's fine but when it 's run standalone the thre... | BackgroundWorker Background = new BackgroundWorker ( ) ; Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler ( DatabaseLoaded ) ; Background.DoWork += new DoWorkEventHandler ( delegate { Database.Load ( ) ; } ) ; Background.RunWorkerAsync ( ) ; | C # : Why is my background worker thread signaling done when it is n't ? |
C# | I have a method which adds row to database ( sql server 2005 ) . Something is wrong with its because , when I have a row with UpdateDate 2000-12-31 23:59:59 it inserts 2001-01-01 00:00:00.000 . Is it possible ? Culture of environment is polish if it is important . It 's a magic for me : / } EDIT : my date : | private void AddInvestmentStatus ( InvestmentData.StatusyInwestycjiRow investmentStatusesRow ) { SqlCommand cmd = new SqlCommand ( `` AddInvestmentStatus '' ) ; cmd.CommandType = CommandType.StoredProcedure ; SqlParameter param1 = new SqlParameter ( `` @ InvestmentId '' , SqlDbType.BigInt ) ; param1.Value = investmentS... | 2001-01-01 00:00:00.000 inserted into database instead 2000-12-31 23:59:59 |
C# | Possible Duplicate : What 's the difference between an object initializer and a constructor ? In c # you can construct an object like : With : or with : What is the diference between that kind of constructors ? | public class MyObject { int val1 ; int val2 ; public MyObject ( int val1 , val2 ) { this.val1 = val1 ; this.val2 = val2 ; } } MyObject ob = new MyObject ( 1,2 ) ; MyObject ob = new MyObject ( ) { val1 = 1 , val2 = 2 } ; | Constructors versus Initializors in C # |
C# | My Silverlight 5 application hosted in an ASP.NET panel is not getting displayed in Firefox ( version 11 ) . However it works perfectly well in Chrome , IE and Safari . I am dynamically loading the Silverlight object as shown below . This is done to pass init parameters . ( which I removed for testing ) . I am getting ... | HtmlGenericControl myHtmlObject = new HtmlGenericControl ( `` object '' ) ; myHtmlObject.Attributes [ `` data '' ] = `` data : application/x-silverlight '' ; myHtmlObject.Attributes [ `` type '' ] = `` application/x-silverlight '' ; HtmlGenericControl mySourceParam = new HtmlGenericControl ( `` param '' ) ; mySourcePar... | Firefox does n't show dynamically added Silverlight 5 control |
C# | Given the following method signature , why is it when a parameter is explicitly named the compiler is unable to automatically infer the type ? Visual Studio 2010 SP1 is able to infer the type and shows no warnings or errors.Calling it as described in CannotInferType and when attempting to compile it the compiler emits ... | IEnumerable < T > ExecuteCommand < T > ( string commandText , string connectionName = null , Func < IDataRecord , T > converter = null ) { ... } static SomeClass Create ( IDataRecord record ) { return new SomeClass ( ) ; } void CannotInferType ( ) { var a = ExecuteCommand ( `` SELECT blah '' , `` connection '' , conver... | Unable to infer generic type with optional parameters |
C# | Has anyone seen a problem in .NET Core 1.1 where beneath the netcoreapp1.1\publish folder they end up with a bin folder that seems to loop on itself and eventually causes a path too long message to appear in Windows . Trying to delete this folder in Windows Explorer cause a Source Too Long message to appear . The only ... | dotnet publish -c debug \publish\bin\debug\netcoreapp1.1\publish\Controllers\Account\Views \publish\bin\debug\netcoreapp1.1\publish\bin\debug\netcoreapp1.1\publish\Controllers\Account\Views | Crazy Deep Path Length in .Net Core 1.1 |
C# | I have defined the following delegate types . One returns a string , and one an object : Now consider the following code : Why is the assignment not valid ? I do not understand . A method which returns a string should be safely considered as a method which returns an object ( since a string is an object ) .In C # 4.0 ,... | delegate object delobject ( ) ; delegate string delstring ( ) ; delstring a = ( ) = > `` foo '' ; delobject b = a ; //Does not compile ! Func < string > a = ( ) = > `` foo '' ; Func < object > b = a ; //Perfectly legal , thanks to covariance in generics delobject b = ( ) = > a ( ) ; delint a = ( ) = > 5 ; delobject b =... | Why does the following example using covariance in delegates not compile ? |
C# | How do you pin to start special folders using powershell ? Like `` ThisPC '' , iexplorerThis will pin to start exe 's fine , but what about windows explorer and myComputer ? How to pin those items since they have no target ? Given thisIt seems to have issues with .lnk 's for `` This PC '' , `` File Explorer '' , etcI t... | < start : DesktopApplicationTile Size= '' 2x2 '' Column= '' 0 '' Row= '' 0 '' DesktopApplicationLinkPath= '' % APPDATA % \Microsoft\Windows\Start Menu\Programs\Windows System\This PC.lnk '' / > Function PinLnk { Param ( [ Parameter ( Mandatory , Position=0 ) ] [ Alias ( ' p ' ) ] [ String [ ] ] $ Path ) $ Shell = New-O... | How To Pin To Start Special Folders With No Target |
C# | I 'm using T4Template and codeDOM to create an assembly using the following code : The Template looks like this ( for moment ) : In the Main application I have a byte array which contains some bytes of a certain application , these bytes are loaded into the array at runtime.My question is : How can I pass the array of ... | CompilerParameters Params = new CompilerParameters ( ) ; Params.GenerateExecutable = true ; Params.ReferencedAssemblies.Add ( `` System.dll '' ) ; Params.OutputAssembly = `` myfile.exe '' ; RuntimeTextTemplate1 RTT = new RuntimeTextTemplate1 ( ) ; string Source = RTT.TransformText ( ) ; CompilerResults Create = new CSh... | Pass an array of bytes to T4 Template code into another array of same type |
C# | When you read MSDN on System.Single : Single complies with the IEC 60559:1989 ( IEEE 754 ) standard for binary floating-point arithmetic.and the C # Language Specification : The float and double types are represented using the 32-bit single-precision and 64-bit double-precision IEEE 754 formats [ ... ] and later : The ... | using System ; static class Program { static void Main ( ) { Console.WriteLine ( `` Environment '' ) ; Console.WriteLine ( Environment.Is64BitOperatingSystem ) ; Console.WriteLine ( Environment.Is64BitProcess ) ; bool isDebug = false ; # if DEBUG isDebug = true ; # endif Console.WriteLine ( isDebug ) ; Console.WriteLin... | Single-precision arithmetic broken when running x86-compiled code on a 64-bit machine |
C# | I need to call a server that exposes an action.This action has either a string of a collection of complex types or a collection of complex types as parameters . I need to call either.Metadata is : either : With the following complex type : Or , alterantively : with the complex types defined asI see no way to work aroun... | < Action Name= '' BulkChange '' IsBound= '' true '' > < Parameter Name= '' bindingParameter '' Type= '' Collection ( PropertyCore.InspectionDuty ) '' / > < Parameter Name= '' Comment '' Type= '' Edm.String '' Unicode= '' false '' / > < Parameter Name= '' Changes '' Type= '' Collection ( PropertyCore.InspectionDutyChang... | C # odata action with complex type collection fails |
C# | I am trying to write my own Game of Life , with my own set of rules . First 'concept ' , which I would like to apply , is socialization ( which basicaly means if the cell wants to be alone or in a group with other cells ) . Data structure is 2-dimensional array ( for now ) .In order to be able to move a cell to/away fr... | Forces from lower left neighbour : down ( 0 ) , up ( 2 ) , right ( 2 ) , left ( 0 ) Forces from right neighbour : down ( 0 ) , up ( 0 ) , right ( 0 ) , left ( 2 ) sum : down ( 0 ) , up ( 2 ) , right ( 0 ) , left ( 0 ) | Looking for ideas how to refactor my algorithm |
C# | I 'm trying to understand how `` this '' gets passed around as a property in C # -6.0 ( VS 2015 ) .My assumption is that when the line : Person secondPerson = firstPerson.myself ; is run , that secondPerson becomes a reference to firstPerson , so when I change the name to `` Bill '' , firstPerson.name and secondPerson.... | using System ; public class Person { private Person instance ; public Person ( ) { instance = this ; } public Person myself { get { return instance ; } set { instance = value ; } } public string name = `` Eddie '' ; } public class Example { public static void Main ( ) { Person firstPerson = new Person ( ) ; Person seco... | How is `` this '' passed in C # |
C# | I 'd like to develop a self training algorithm for a specific problem . To keep things simple i 'll nail it down to simple example.Update : I have added a working solution as answer to this question below.Let 's say i have a huge list of entities coming from a database . Each entity is of the same type and has 4 proper... | public class Entity { public byte Prop1 { get ; set ; } public byte Prop2 { get ; set ; } public byte Prop3 { get ; set ; } public byte Prop4 { get ; set ; } } [ Flags ] public enum EEntityValues { Undefined = 0 , Prop1 = 1 , Prop2 = 2 , Prop3 = 4 , Prop4 = 8 , } public static int GetMaxValue < T > ( ) where T : struct... | Self Training Algorithm |
C# | The compiler complains : Can not implicitly convert type 'System.Collections.Generic.List < Tests.Program.FooStruct > ' to 'System.Collections.Generic.IEnumerable < Tests.Program.IFoo > ' . An explicit conversion exists ( are you missing a cast ? ) Why ? Why is there a difference between classes and structs ? Any worka... | private static void TestStructInterface ( ) { IFoo foo1 = new FooClass ( ) ; // works IFoo foo2 = new FooStruct ( ) ; // works IEnumerable < IFoo > foos1 = new List < FooClass > ( ) ; // works IEnumerable < IFoo > foos2 = new List < FooStruct > ( ) ; // compiler error } interface IFoo { string Thing { get ; set ; } } c... | Struct vs class implementing an interface |
C# | I have the following code : Where : What this code does is execute certain SQL statement across a multitude of db connections , where some connections may belong to one DB server , while others - to another and so on.The code makes sure that two conditions hold : The SQL statements are run in parallel across the availa... | innerExceptions = dbconnByServer .AsParallel ( ) .WithDegreeOfParallelism ( dbconnByServer.Count ) // A stream of groups of server connections proceeding in parallel per server .Select ( dbconns = > dbconns.Select ( dbconn = > m_sqlUtilProvider.Get ( dbconn ) ) ) // A stream of groups of SqlUtil objects proceeding in p... | How should I propagate task exception from continuation task in .NET 4.0 ? |
C# | I have this code : and I want to refactor the code separating the key / function definition from theactions . Key.xxx and Function.xxx are n't from the same type.eg : in Python , I could simply do something like : What 's `` the right way '' to do in C # ? | if ( PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState ( Key.Orange ) == KeyState.Lock ) PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand ( Function.Orange , 0 , 0 ) ; if ( PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState ( Key.Blue ) == KeyState.Lock ) PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand ( ... | What 's the C # pattern to perform an action on a series of values ? |
C# | I noticed that a struct wrapping a single float is significantly slower than using a float directly , with approximately half of the performance.However , upon adding an additional 'extra ' field , some magic seems to happen and performance once again becomes more reasonable : The code I used to benchmark these is as f... | using System ; using System.Diagnostics ; struct Vector1 { public float X ; public Vector1 ( float x ) { X = x ; } public static Vector1 operator + ( Vector1 a , Vector1 b ) { a.X = a.X + b.X ; return a ; } } struct Vector1Magic { public float X ; private bool magic ; public Vector1Magic ( float x ) { X = x ; magic = t... | Why does adding an extra field to struct greatly improves its performance ? |
C# | Has anyone tried to stack contexts and use Tasks at the same time ? I 'm trying something like this : and I 'm getting that result : I was expecting it to have [ Saving Data ] instead of [ ( null ) ] on the second line.It appears to lose access to the log4net ThreadContext Stack as soon as it starts a new Task.Do you k... | using ( log4net.ThreadContext.Stacks [ `` contextLog '' ] .Push ( `` Saving Data '' ) ) { log.Info ( `` Starting transaction '' ) ; var taskList = new List < Task > ( ) ; taskList.Add ( Task.Factory.StartNew ( ( ) = > { log.Info ( `` Inside Transaction '' ) ; } ) ) ; Task.WaitAll ( taskList.ToArray ( ) ) ; } 2015/42/26... | Conflict between Log4Net 's ThreadContext and Task |
C# | I have this [ nasty ] regex to capture a VBA procedure signature with all the parts in a bucket : Part of it is overkill and will match illegal array syntaxes ( in the context of a procedure 's signature ) , but that 's not my concern right now.The problem is that this part : breaks when a function ( or property getter... | public static string ProcedureSyntax { get { return @ '' ( ? : ( ? < accessibility > Friend|Private|Public ) \s ) ? ( ? : ( ? < kind > Sub|Function|Property\s ( Get|Let|Set ) ) ) \s ( ? < identifier > ( ? : [ a-zA-Z ] [ a-zA-Z0-9_ ] * ) | ( ? : \ [ [ a-zA-Z0-9_ ] *\ ] ) ) \ ( ( ? < parameters > .* ) ? \ ) ( ? : \sAs\s ... | Parsing signatures with regex , having `` fun '' with array return values |
C# | I have a weighted choice algorithm that works , but I 'd like to improve it in two aspects ( in order of importance ) : Guarantee that a minimum number from each possible choice is chosen.Reduce computational complexity from O ( nm ) to O ( n ) or O ( m ) , where n is the requested number of randomly chosen items and m... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Security.Cryptography ; public class Program { static void Main ( string [ ] args ) { // List of items with discrete availability // In this example there is a total of 244 discrete items and 3 types , // but there co... | Constrained weighted choice |
C# | To reproduce : Download https : //github.com/nventive/Uno.QuickStartAdd a .NETStandard2_0 project called TestMe.Reference TestMe in the MyApp.Droid project.Building MyApp.Droid brings compile error : System.InvalidOperationException : The project ( s ) TestMe did not provide any metadata reference . This may be due to ... | < TargetFrameworks > net461 ; netstandard2.0 < /TargetFrameworks > < TargetFrameworks > net47 ; netstandard2.0 < /TargetFrameworks > | Referencing a .netstandard2_0 project in a platform.uno project |
C# | Consider the following benchmark : BenchmarkDotNet reports the following results on .net framework 4.8 and .net core 3.1 : From the result , it seems that GetEnumerator causes a heap allocation when the array is not empty , but not when the array is empty . I 've rewritten the benchmark in many different ways but alway... | [ MemoryDiagnoser ] public class EnumerableBenchmark { private IEnumerable < string > _emptyArray = new string [ 0 ] ; private IEnumerable < string > _notEmptyArray = new string [ 1 ] ; [ Benchmark ] public IEnumerator < string > ArrayEmpty ( ) { return _emptyArray.GetEnumerator ( ) ; } [ Benchmark ] public IEnumerator... | Why does enumerating an empty array does not allocate on the heap ? |
C# | One of the things that you have beaten into you as a junior developer is that you never , ever do a `` SELECT * '' on a data set , as it is unreliable for several reasons.Since moving over to Linq ( firstly Linq to SQL and then the Entity Framework ) , I have wondered if the Linq equivalent is equally frowned upon ? Eg... | var MyResult = from t in DataContext.MyEntity where t.Country == 7 select t ; | Linq no-noes - the catch all sql-like select ? |
C# | I have a few infinite generator methods , including some long-running and infinitely-long-running generators.My goal is to have an infinite sequence that combines the items from the two examples . Here 's what I tried , using PLINQ : This seems appropriately combines the two IEnumerables into a new one , with items fro... | IEnumerable < T > ExampleOne ( ) { while ( true ) // this one blocks for a few seconds at a time yield return LongRunningFunction ( ) ; } IEnumerable < T > ExampleTwo ( ) { while ( true ) //this one blocks for a really long time yield return OtherLongRunningFunction ( ) ; } IEnumerable < T > combined = new [ ] { Exampl... | Pitfalls of trying to use PLINQ over long-running generators ? |
C# | I was looking at some code I 've inherited and I could n't decided if I like a bit of code.Basically , there is a method that looks like the following : It returns true if it connects successfully , false otherwise.I 've written code like that in the past , but now , when I see this method I do n't like it for a number... | bool Connect ( connection parameters ) { ... } void Connect ( Connection Parameters , out bool successful , out string errorMessage ) { ... } | Should a connect method return a value ? |
C# | Problem : We make extensive use of a repository pattern to facilitate read/write operations on our datastore ( MS SQL using LINQ ) across multiple applications and subsections of functionality . We have series of methods that all do something similar to each other.For example , we have the ProcessAndSortXXXXX class of ... | private static IEnumerable < ClassErrorEntry > ProcessAndSortClassErrorLog ( IQueryable < ClassErrorDb > queryable , string sortOrder ) { var dynamic = queryable ; if ( ! String.IsNullOrEmpty ( sortOrder.Trim ( ) ) ) { dynamic = dynamic.OrderBy ( sortOrder ) ; } return dynamic .Select ( l = > new ClassErrorEntry ( l.Id... | Building a common set of methods that can operate on any linq table |
C# | Let 's say I have some basic interface which is generics-driven : Now I have some concrete implementation of this interface which is also generic : This looks OK , but now let 's say I have other class : And let 's say I want to perform a check if TShouldModelInterface actually implements any of the possible Interface ... | public interface Inteface < T > { void Foo ( T t ) ; } public class InterfaceImpl < T > { public void Foo ( T t ) { // Whatever } } public class Ololo { public void BadFunction < TShouldModelInterface > ( TShouldModelInterface shouldModelInterface ) { // Whatever } } | C # generics question - generic interface constraint |
C# | To start with , this is not the same as Why is Func < > created from Expression > slower than Func < > declared directly ? and is surprisingly just the opposite of it . Additionally , all links and questions that I have found while researching this issue all originate out of the 2010-2012 time period so I have decided ... | [ CoreJob , ClrJob , DisassemblyDiagnoser ( true , printSource : true ) ] public class Delegates { readonly DelegatePair < string , string > _empty ; readonly DelegatePair < string , int > _expression ; readonly string _message ; public Delegates ( ) : this ( new DelegatePair < string , string > ( _ = > default , _ = >... | Why Is a Compiled Delegate Faster Than a Declared Delegate ? |
C# | It is possible to bind actions ' parameters via : [ FromBody ] Request body [ FromForm ] Form data in the request body [ FromHeader ] Request header [ FromQuery ] Request query string parameter [ FromRoute ] Route data from the current request [ FromServices ] I often need to extract something from a JWT , almost alway... | var id = int.Parse ( base.User.FindFirst ( ClaimTypes.NameIdentifier ) ? .Value ) ; public IActionResult doStuff ( [ FromBody ] MyModel model , [ FromJwt ] int id ) { // id works automatically } | Bind ASP.NET Core action parameter to JWT claim |
C# | I have tried to search for the duplicates of my problem , but could not find . Also , sorry for the not so understandable title . I am so confused about what I am searching , and also about the terminology . I am an electronics engineer with very little knowledge on .Net framework , so treat me well : ) My current proj... | 0x1E 0x21 0x01 0x13 0x14 0x35 0x46 0x1E 0x21 0x01 0x13 0x14 0x43 0x48 0x0A 0x0D Record start.21.01.13 14:35Heart Rate : 70Record start.21.01.13 14:43Heart Rate : 72End of records . | How to convert string to int then to string ? |
C# | I do not know how to describe my problem , but imagine having a TextBox in WPF with a long text . I have set TextWrapping= '' Wrap '' to prevent the whole string being displayed in one line , but I want my sting to be shown as follows : Instead of this : The difference is , that the first text has a 'hard cut ' after e... | Lorem ipsum dolor sit amet , consectetur adipiscing elit . Fusce ligula nulla , cursus finibus mauris vel , rhoncus blandit sem . Fusce fermentum sed sem a porttitor . Proin id convallis ex . Lorem ipsum dolor sit amet , consectetur adipiscingelit . Fusce ligula nulla , cursus finibus mauris vel , rhoncus blandit sem .... | Break words in textbox ( with TextWrapping=Wrap ) |
C# | We all know that the using statement is really good for resources you want to cleanup in a timely manner , such as an open file or database connection.I was wondering if it would be considered a good thing to use the statement in cases where resources cleanup is n't the goal of the Dispose ( ) method , but rather reset... | class CursorHelper : IDisposable { readonly Cursor _previousState ; public CursorHelper ( Cursor newState ) { _previousState = Cursor.Current ; Cursor.Current = newState ; } public void Dispose ( ) { Cursor.Current = _previousState ; } } public void TimeIntensiveMethod ( ) { using ( CursorHelper ch = new CursorHelper (... | Using 'Using ' for things other than resource disposal |
C# | During answering on one of questions I saw 2 examples of LINQ code which should work exactly same . But I was wonder about performance , and found that one code much faster that another code . And I can not understand why . I took datastructures from questionthen I wrote simple benchmark tests ( used benchmarkdotnet li... | public struct Strc { public decimal A ; public decimal B ; // more stuff } public class CLASS { public List < Strc > listStrc = new List < Strc > ( ) ; // other stuff } public class TestCases { private Dictionary < string , CLASS > dict ; public TestCases ( ) { var m = 100 ; var n = 100 ; dict = Enumerable.Range ( 0 , ... | Linq to objects : inner query performance |
C# | I 've been struggling to adapt my standard approach for test-driving .NET code to Ruby.As an example , I am writing a class that will : Normally for .NET I 'd end up with something like : In my test ( written first ) , I 'd mock finder and converter . Then I 'd stub out finder.FindFiles ( `` *.markdown '' ) to return s... | grab all *.markdown files from a directory foreach file : extract code samples from file save code to file.cs in output directory class ExamplesToCode { public ExamplesToCode ( IFileFinder finder , IExampleToCodeConverter converter ) { ... } public void Convert ( string exampleDir , string targetDir ) { ... } } | How to move from .NET-style TDD to Ruby ? |
C# | My application receives push notifications well when the application is closed . But when the app is running , I get nothing . This is the same code that I have used in previous apps with out any problems , those were on WindowsPhone8 and the new apps are running on WindowsPhone8.1 devices.I used this Push Tutorial whe... | HttpNotificationChannel pushChannel ; string channelName = `` PushChannel '' ; pushChannel = HttpNotificationChannel.Find ( channelName ) ; //Push Notificationsif ( pushChannel == null ) { pushChannel = new HttpNotificationChannel ( channelName ) ; //// Register for all the events before attempting to open the channel ... | PUSH not showing when App is open |
C# | I am a beginner to C # and I am picking it up by solving data structures case scenarios . I need help visualizing what is happening in the following code snippet What part I have understood I am aware that a new node is being added at the end of the linked list . Also , the new node is getting its value from the functi... | public void AddAtLast ( object data ) { Node newNode = new Node ( ) ; newNode.Value = data ; current.Next = newNode ; current = newNode ; Count++ ; } | Linked Lists : When adding a element why is current.Next pointing to the new Node , and why do we overwrite the Current Node |
C# | Suppose I have written such a class ( number of functions does n't really matter , but in real , there will be somewhere about 3 or 4 ) .I wonder if the C # compiler can optimize such a code so that it wo n't go through numerous stack calls.Is it able to inline delegates at compile-time at all ? If yes , on which condi... | private class ReallyWeird { int y ; Func < double , double > f1 ; Func < double , double > f2 ; Func < double , double > f3 ; public ReallyWeird ( ) { this.y = 10 ; this.f1 = ( x = > 25 * x + y ) ; this.f2 = ( x = > f1 ( x ) + y * f1 ( x ) ) ; this.f3 = ( x = > Math.Log ( f2 ( x ) + f1 ( x ) ) ) ; } public double Calcu... | Delegate stack efficiency |
C# | Is there a difference between the following two pieces of code ? I found that our code base uses the second way of writing . | class Test { public readonly double Val ; public Test ( bool src ) { this.Val = src ? 1 : 0 ; } } class Test { public readonly double Val ; public Test ( bool src ) { this.Val = src ? 1D : 0D ; } } | Is there a difference between `` double val = 1 ; '' and `` double val = 1D ; '' ? |
C# | I have a Silverlight app that uses actions to get data from the model ( which again gets the data from WCF services ) .I need to somehow sync two ActionCallbacks , or wait for them , and then execute some code.Example : I know I can use a counter to keep track of how many has returned , but is there not a better way to... | _model.GetMyTypeList ( list = > { MyTypeList.AddRange ( list ) ; } ) ; _model.GetStigTypeList ( list = > { StigTypeList.AddRange ( list ) ; } ) ; doSomethingWhenBothHaveReturned ( ) ; | Syncronizing actions in Silverlight |
C# | Recently I edit C # code in vim . And the build system has StyleCop enabled so that all using statement should be in alphabetical order.So , I tried to select below lines of code in visual mode , then type `` : sort '' .The result is : It does n't pass StyleCop checking because `` System.Security '' is not ahead of `` ... | using System.Security.Permissions ; using System.Runtime.Serialization ; using System.Security ; using System.ServiceModel ; using System.Runtime.Serialization ; using System.Security.Permissions ; using System.Security ; using System.ServiceModel ; using System.Runtime.Serialization ; using System.Security ; using Sys... | How to sort using statement of C # code in vim ? |
C# | There is a view displaying 5 dropdown lists populated with all available courses from relevant table : Student will select one course from each dropdown lists and press Register button.My question is how I will get selected courses in relevant controller ? Thanks . | @ model StudentRegistrationPortal.Models.CourseRegisterModel @ { ViewBag.Title = `` registerCourses '' ; } < h2 > Welcome @ Context.User.Identity.Name < /h2 > @ Html.ActionLink ( `` [ Sign Out ] '' , `` SignOut '' , `` Admin '' ) @ using ( Html.BeginForm ( ) ) { @ Html.ValidationSummary ( true ) < fieldset > < legend >... | Get selected values from multiple selectlists in MVC3 controller |
C# | I wrote this simple linq-to-xml query and it seems that null exception could not be avoided using the the linq syntax . Am I using it wrong ? What should be the right ( and short ) Linq2Xml syntax ? The linq2Xml queryThe XML | var userData = queryUserResponseData.Elements ( `` user '' ) .Single ( u = > u.Element ( `` username '' ) .Value == userName ) ; < data > < user > < username > User1 < /username > < userid > 123 < /userid > < /user > < user > < username > User2 < /username > < userid > 456 < /userid > < /user > < user > < userid > 999 ... | How to use linq2Xml without the possibility of a null exception ? |
C# | I have noticed the following enum declaration while browsing some sample code . What does None=1 mean ? | public enum ButtonActions { None = 1 , Clear , Insert , Delete , Cancel , Close } | What does None=1 refer in the following enum class ? |
C# | I have a form with two custom panels and I 'm adding some labels to them and in the end i want they to scroll from the right to the left but they are just stucking in the same position.There is a screenshot of what i haveThere are two panels and the 4 labels and they just stay stuck in there ... This is the code in my ... | private MyPanel topPanel ; // the red bar private MyPanel botPanel ; // the white bar public SmsBar ( ) { InitializeComponent ( ) ; this.Width = 500000 ; this.Location = new Point ( x , y ) ; topPanel = new MyPanel ( System.Drawing.Color.White , System.Drawing.Color.Red , ( new Font ( `` Tahoma '' , 10 , FontStyle.Bold... | c # flow layout labels got stuck |
C# | I want to understand the difference between andI actually want to understand what is the benefit of creating a new object using `` using '' instead of creating it directly like this | public DataTable ExectNonActQuery ( string spname , SqlCommand command ) { using ( DataTable dt = new DataTable ( ) ) { cmd = command ; cmd.Connection = GetConnection ( ) ; cmd.CommandText = spname ; cmd.CommandType = CommandType.StoredProcedure ; da.SelectCommand = cmd ; da.Fill ( dt ) ; return ( dt ) ; } } public Dat... | What is the benefit of `` using '' |
C# | I was recently reviewing some code written by two different contractors , both were basic ASP.NET management sites . The sites allowed the user to view and edit data . Pretty much simple CRUD gateways.One group did their best to use built in ASP + AJAX Toolkit controls and did their best to use as many built in control... | < script id= '' HRPanel '' type= '' text/html '' > < table cellpadding= ' 0 ' cellspacing= ' 0 ' class= '' atable '' > < thead class= '' mHeader '' > < tr > < th > Name < /th > < th > Description < /th > < th > Other < /th > < /thead > < tbody > < # for ( var i=0 ; i < hrRows.length ; i++ ) { var r = HRRows [ i ] ; # >... | Best practices for developing simple ASP.NET sites ( built in controls or JQuery + scripts ) |
C# | Sorry if this is a really basic question but it 's been really getting to me . I really like the idea of DI , it really helps me with my testing but I have hit a bit of a brick wall I think . So I have two types : Now the table object has a constructor on it like this : Now the table object pretty much only uses those ... | Table TableManager Table ( ITableCommandRunner tableRunner , IQueryProvider queryProvider , IDataReader reader , string Name ) TableManager ( ITableCommandRunner tablrunner ) public ITable OpenTable ( string tableName ) { // Call open table command on tablerunner . // I need a IQueryProvider and IDataReader to pass to ... | DI object graph building - separating logic and construction graph |
C# | Now with C # 7 , we can return by ref with return ref . From what I 've gathered , references are 32 or 64 bits . Now , if I had a struct Coord with a long X and long Y , that would be 128 bits , so it 'd be easier return the coord , ( as well as pass it ) by reference to avoid copying the 128 bits . On the other hand ... | // This size is 128 bytes , which is 2 or 4x larger than the size of a referencepublic struct Coord { public long X , Y ; } private Coord myCoord ; // This will return the Coord by value , meaning copying the full 128 bytespublic Coord GetCoordValue ( ) = > myCoord ; // This will return the Coord by reference , meaning... | Should we always return by ref if we can ? |
C# | Ok so after reading Albahari 's Threading in C # , I am trying to get my head around Thread.MemoryBarrier ( ) and Out-of-Order Processing.Following Brian Gideon 's answer on the Why we need Thread.MemoerBarrier ( ) he mentions the following code causes the program to loop indefinitely on Release mode and without debugg... | class Program { static bool stop = false ; public static void Main ( string [ ] args ) { var t = new Thread ( ( ) = > { Console.WriteLine ( `` thread begin '' ) ; bool toggle = false ; while ( ! stop ) { // Thread.MemoryBarrier ( ) or Console.WriteLine ( ) fixes issue toggle = ! toggle ; } Console.WriteLine ( `` thread... | Explanation of Thread.MemoryBarrier ( ) Bug with OoOP |
C# | I was looking at the Routing Concepts of MVC and specifically at the below line : Everything 's fine , but I do n't get the significance of the Route Name.Is it just a term out there ? or is there anything significant with it ? Am I missing using it or where are the places it is used in MVC 4 ? Thanks in advance . | routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // Route Pattern new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } // Default values . ) ; | Significance of the Route Name in MVC 4 |
C# | I have much more experience in Spring and Java , but now I am working on ASP.NET Web API project.So in Spring there is @ JsonView annotation with which I can annotate my DTOs , so I could select which data I will show through REST . And I find that very useful . But I can not find any equivalent in ASP.NET . So I would... | public class UserEntity { @ JsonView ( Views.Public.class ) @ JsonProperty ( `` ID '' ) private Integer id ; @ JsonView ( Views.Public.class ) private String name ; @ JsonView ( Views.Admin.class ) @ JsonFormat ( shape = JsonFormat.Shape.STRING , pattern = `` dd-MM-yyyy hh : mm : ss '' ) private Date dateOfBirth ; @ Js... | Is there @ JsonView equivalent in ASP.NET Web API |
C# | Do Volatile.Read and Volatile.Write have the exact same effect on a nonvolatile int that normal reads and assignments have on an int with the volatile modifier ? The motivation is to prevent the warning that volatile variables should not be passed via ref parameters to the Interlocked methods . ( I understand that the ... | //private volatile int suppressListChangedEvents ; private int suppressListChangedEvents ; public void SuppressListChangedEvents ( ) { Interlocked.Increment ( ref suppressListChangedEvents ) ; } public void UnsuppressListChangedEvents ( ) { if ( Interlocked.Decrement ( ref suppressListChangedEvents ) < 0 ) throw new In... | What is the difference between the volatile modifier and Volatile.Read/Write ? |
C# | Suppose I have two functions which look like this : What would be a good way to avoid repeated dostuff ? Ideas I 've thought of , but do n't like : I could make d an object and cast at runtype based on type , but this strikes me as not being ideal ; it removes a type check which was previously happening at compile time... | public static void myFunction1 ( int a , int b , int c , string d ) { //dostuff someoneelsesfunction ( c , d ) ; //dostuff2 } public static void myFunction2 ( int a , int b , int c , Stream d ) { //dostuff someoneelsesfunction ( c , d ) ; //dostuff2 } | Reducing Code Repetition : Calling functions with slightly different signatures |
C# | I was looking at the memory impact of a simple LINQ query and noticed that the LINQ query created 2 extra objects of types Enumerable+WhereListIterator < Int32 > and Func < Int32 , Boolean > . The code used is this : At the snapshot after the foreach loop I notice that the Enumerable+WhereListIterator < Int32 > object ... | static void Main ( string [ ] args ) { // Setting baseline snapshot var list1 = new List < int > { 4862 , 6541 , 7841 } ; var list2 = new List < int > ( list1.Count ) ; var list3 = new List < int > ( list1.Count ) ; // First snapshot : LINQ usage list2.AddRange ( list1.Where ( item = > item > 5000 & & item < 7000 ) ) ;... | Why does a GC after a LINQ query free the WhereListIterator but not the Func representing the condition ? |
C# | For example , we have two domain objects : Cell and Body ( as in human cell and body ) .The Body class is just a collection of Cells , e.g.The Cell has a Split method , which internally creates a clone of itself , e.g.Now , in DDD when the cell splits should : The cell add the newly created cell to the Body ( which wou... | class Body { IList < Cell > cells ; public void AddCell ( Cell c ) { ... } public void RemoveCell ( Cell c ) { ... } } Class Cell { public Cell Split ( ) { Cell newCell = new Cell ( ) ; // Copy this cell 's properties into the new cell . return Cell ; } } | In Domain Driven Design when an entity clones itself who adds it to its container ? |
C# | Possible Duplicate : What 's the use/meaning of the @ character in variable names in C # ? C # prefixing parameter names with @ I feel like I should know this and I find it impossible to google.Below is an excerpt from some Linq code I came across : What does the ' @ ' prefix mean in this context ? | private static readonly Func < SomeEntities , someThing , List < someThing > > GetReplacement = ( someEntities , thing ) = > someEntities.someReplacement.Join ( someEntities.someThing , replaces = > replaces.new_thing_id , newThing = > newThing.thing_id , ( rep , newThing ) = > new { rep , newThing } ) .Where ( @ t = >... | Linq , lambda and @ |
C# | I have a function to generate an expression to be used in a linq Where clause . ( note IActive only defines the property 'Active ' ) There are other related functions and the idea is that i can inject the required conditions into a Generic class to control business rules , etc.The problem is that when I run this , the ... | public static Expression < Func < T , bool > > GetWhereCondition < T > ( ) where T : IActive { return x = > x.Active ; } x = > Convert ( x ) .Active | Expression < Func < T , bool > > adds an unwanted Convert when created in generic method |
C# | I have an enum which describes options available for a user to select as part of settings . This is serialized to XML . One of the names is not ideal , and I 'd like to rename it , but still support deserialization of older settings files.For example : I know I can rename it but specify the previous serialized name lik... | public enum Options { Odd , NonOdd // rename to 'Even ' } public enum Options { Odd , [ XmlEnum ( Name = `` NonOdd '' ) ] Even } | How can I rename an enum which is serialized to XML but continue to support previous names ? |
C# | I 'm trying the following code.. I get the following error : Query operator 'Count ' is not supported . I want to basically be able to specify a Where In clause instead of Where =.Anyone has an idea of how I can achieve this ? | LoadOperation < Tasks > PhasesLP = context . Load ( context.GetTasksQuery ( ) . Where ( o= > ProjectList.Where ( p= > p.ProjectID == o.ProjectID ) .Count ( ) == 1 ) | WCF RIA - Query operator 'Count ' is not supported |
C# | I use the `` is '' operator to find a certain class : This works fine especially as it finds any class that inherits from the ScreenBase but not the base classes from ScreenBase.I would like to do the same when I know only the Type and do n't want to instantiate the class : But this comparsion produces a warning as it ... | for ( int i=0 ; i < screens.Count ; i++ ) { if ( screen is ScreenBase ) { //do something ... } } Type screenType = GetType ( line ) ; if ( screenType is ScreenBase ) | `` is '' - operator for Type |
C# | After adding < Nullable > enable < /Nullable > or # nullable enable , I ran into the following problem with my Generic methods : This does not work : This works with warning : This works individually , but not together.Logically , the first method should work.What is the correct way ( in any framework ) out of this sit... | public T ? GetDefault < T > ( ) { return default ; } public T GetDefault < T > ( ) { return default ; } public T ? GetDefault < T > ( ) where T : class { return default ; } public T ? GetDefault < T > ( ) where T : struct { return default ; } | A problem with Nullable types and Generics in C # 8 |
C# | When attempting to use the C # `` as '' keyword against a non-generic type that can not be cast to , the compiler gives an error that the type can not be converted.However when using the `` as '' keyword against a generic type the compiler gives no error : I discovered this behaviour in a much larger code base where th... | public class Foo { } public class Bar < T > { } public class Usage < T > { public void Test ( ) { EventArgs args = new EventArgs ( ) ; var foo = args as Foo ; // Compiler Error : can not convert type var bar = args as Bar < T > ; // No compiler error } } | Conflicting compile time behaviour using as keyword against generic types in C # |
C# | Possible Duplicate : String concatenation vs String Builder . Performance Any difference ( performance and memory usage ) between the following two options ? option 1 : options 2 : | StringBuilder msgEntry = new StringBuilder ( ) ; msgEntry.AppendLine ( `` < `` + timeTag + `` > '' + timeStamp + `` < / '' + timeTag + `` > '' ) ; StringBuilder msgEntry = new StringBuilder ( ) ; msgEntry.Append ( `` < `` ) ; msgEntry.Append ( timeTag ) ; msgEntry.Append ( `` > '' ) ; msgEntry.Append ( timeStamp ) ; ms... | which string operation is better ? |
C# | I 'm looking to create a function that accepts any task that produces an IEnumerable < T > . To illustrate , consider the following function signature.Now , I would like to call this method as follows : Clearly , this does n't work since the two Task types are not the same , and that covariance does n't exist for Tasks... | void DoWork < TElement > ( Task < IEnumerable < TElement > > task ) { } Task < int [ ] > task = Task.FromResult ( new [ ] { 1 , 2 , 3 } ) ; DoWork ( task ) ; async Task < IEnumerable < int > > GetTask ( ) { return await Task.FromResult ( new int [ ] { 1 , 2 , 3 } ) ; } // Service proxy methodTask < int [ ] > GetInts ( ... | How do I define a function that accepts any Task producing an IEnumerable < T > ? |
C# | I have a class defined as : When I run Node.Load ( ) from a codebehind ( Window.xaml.cs ) the Node 's static constructor never fires ; or at least does n't hit a breakpoint and does not set Node.Query to anything other than null.Is there any reason why this might occur ? SolutionCheck out the answers below for a few so... | public class DatabaseEntity < T > where T : DatabaseEntity < T > { public static string Query { get ; protected set ; } public static IList < T > Load ( ) { return Database.Get ( Query ) ; } } public class Node : DatabaseEntity < Node > { static Node ( ) { Node.Query = @ '' SELECT Id FROM Node '' ; } } | Child static constructor not called when base member accessed |
C# | I have a use case where the text has to be encoded and sent using the AES 256 algorithm . The client-side code is in C # which would be decrypting the code.Encryption code in JS : Updated code used in the client side : The keyString and IV value used are same in C # and is encrypted using Utf8 . Looking for the equival... | const crypto = require ( 'crypto ' ) ; algorithm = 'aes-256-cbc ' , secret = '1234567890123456 ' , keystring = crypto.createHash ( 'sha256 ' ) .update ( String ( secret ) ) .digest ( 'base64 ' ) .substr ( 0 , 16 ) ; iv = crypto.createHash ( 'sha256 ' ) .update ( String ( secret ) ) .digest ( 'base64 ' ) .substr ( 0 , 1... | AES encryption in Node JS and C # gives different results |
C# | Suppose I have a custom collection class that provides some internal thread synchronization . For instance , a simplified Add method might look like this : The latest Code Contracts complains that CodeContracts : ensures unproven : this.Count > = Contract.OldValue ( this.Count ) . The problem is that this really ca n't... | public void Add ( T item ) { _lock.EnterWriteLock ( ) ; try { _items.Add ( item ) ; } finally { _lock.ExitWriteLock ( ) ; } } | Collection Contracts and Threading |
C# | Sample String The regex should match and should not match [ 000112 ] since there is outer square bracket.Currently I have this regex that is matching [ 000112 ] as well | `` [ ] [ ds* [ 000112 ] ] [ 1448472995 ] sample string [ 1448472995 ] *** '' ; [ 1448472995 ] [ 1448472995 ] const string unixTimeStampPattern = @ '' \ [ ( [ 0-9 ] + ) ] '' ; | Regex to get square brackets containing numbers only but are not within square brackets themselves |
C# | Possible Duplicate : What is the = > token called ? Hey , In LINQ what is the name of the = > operator e.g : | list.Where ( a = > a.value == 5 ) ; | The name of the = > operator in C # |
C# | Recently I started working on trying to mass-scrape a website for archiving purposes and I thought it would be a good idea to have multiple web requests working asynchronously to speed things up ( 10,000,000 pages is definitely a lot to archive ) and so I ventured into the harsh mistress of parallelism , three minutes ... | static void Main ( string [ ] args ) { for ( int i = 0 ; i < 10 ; i++ ) { int i2 = i + 1 ; Stopwatch t = new Stopwatch ( ) ; t.Start ( ) ; Task.Factory.StartNew ( ( ) = > { t.Stop ( ) ; Console.ForegroundColor = ConsoleColor.Green ; //Note that the other tasks might manage to write their lines between these colour chan... | Asynchronous Tasks 'Clogging ' |
C# | I 've just found a bug in my program ( after some amount of debugging and tearing my hair ) As you can see firstis always true - never changed . So if ( ! first ) is basically if ( false ) .The compiler did not generate a warning although it is set to level 4 ( highest level ) .How can I find similar if ( false ) error... | bool first = true ; foreach ( RdAbstractNode node in listNodes ) { if ( ! first ) { // do stuff ( does not change first ) } // do more stuff ( does not change first ) } | c # : Finding Bugs : if ( false ) |
C# | Sample code to illustrate : I 'm seeing res1 = -1 , and res2 = 1 at the end , which was a bit unexpected . I thought res1 would return 1 , since on an ASCII chart `` A '' ( 0x41 ) comes before `` a '' ( 0x61 ) . Also , it seems strange that for res2 , the length of the string seems to make a difference . i.e . if `` a ... | int res1 = `` a '' .CompareTo ( `` A '' ) ; // res1 = -1 int res2 = `` ab '' .CompareTo ( `` A '' ) ; // res2 = 1 | String.CompareTo with case |
C# | HashSet.Contains implementation in .Net is : And I read in a lot of places `` search complexity in hashset is O ( 1 ) '' . How ? Then why does that for-loop exist ? Edit : .net reference link : https : //github.com/microsoft/referencesource/blob/master/System.Core/System/Collections/Generic/HashSet.cs | /// < summary > /// Checks if this hashset contains the item /// < /summary > /// < param name= '' item '' > item to check for containment < /param > /// < returns > true if item contained ; false if not < /returns > public bool Contains ( T item ) { if ( m_buckets ! = null ) { int hashCode = InternalGetHashCode ( item... | How can hashset.contains be O ( 1 ) with this implementation ? |
C# | I have two large lists of object . First ( about of 1 000 000 objects ) : Second ( about of 20 000 objects ) : I need to find all Traider items in Base items when DateUtc are equals and Fee are equals . Now i am using Any method : But this way is very-very slow . Is there a way to make this more efficient ? Is there po... | public class BaseItem { public BaseItem ( ) { } public double Fee { get ; set ; } = 0 ; public string Market { get ; set ; } = string.Empty ; public string Traider { get ; set ; } = string.Empty ; public DateTime DateUtc { get ; set ; } = new DateTime ( ) ; } public class TraiderItem { public TraiderItem ( ) { } public... | Filter large list object on data from another large list : slow performance |
C# | I am aware of the constructor difficulty in Xamarin Android as is explained here : No constructor found for ... ( System.IntPtr , Android.Runtime.JniHandleOwnership ) and all the fragments & activities & other custom views that I create in the app import this constructor.Sometimes however a null reference exception is ... | public class TestView : Android.Support.V4.App.Fragment { public TestClass _testClass ; public TestView ( TestClass testClass ) { this._testClass = testClass ; } public TestView ( IntPtr javaReference , Android.Runtime.JniHandleOwnership transfer ) : base ( javaReference , transfer ) { } public override Android.Views.V... | Will Xamarin Android execute OnCreateView when the IntPtr constructor is called ? |
C# | I have a large third party webservice ; the reference.cs is 33 Mbyte . Using Visual Studio 2017 , the proxy uses the XML Serializer , which causes a 5 second delay when creating the channel . I opened a case at Microsoft , and they showed me partially how to modify the reference.cs to use the Datacontract serializer . ... | public XmlMembersMapping ImportMembersMapping ( string elementName , string ns , XmlReflectionMember [ ] members , bool hasWrapperElement , bool writeAccessors , bool validate , XmlMappingAccess access ) { ElementAccessor element = new ElementAccessor ( ) ; element.IsSoap = true ; element.Name = elementName == null || ... | Can the data contract serializer used for any third party webservice |
C# | I am reading this blog : Pipes and filters patternI am confused by this code snippet : what is the purpose of this statement : while ( enumerator.MoveNext ( ) ) ; ? seems this code is a noop . | public class Pipeline < T > { private readonly List < IOperation < T > > operations = new List < IOperation < T > > ( ) ; public Pipeline < T > Register ( IOperation < T > operation ) { operations.Add ( operation ) ; return this ; } public void Execute ( ) { IEnumerable < T > current = new List < T > ( ) ; foreach ( IO... | Help me understand the code snippet in c # |
C# | When coding C # I often find myself implementing immutable types . I always end up writing quite a lot of code and I am wondering whether there is a faster way to achieve it.What I normally write : This gets fairly complicated when the number of fields grows and it is a lot of typing . Is there a more efficient way for... | public struct MyType { private Int32 _value ; public Int32 Value { get { return _value ; } } public MyType ( Int32 val ) { _value = val ; } } MyType alpha = new MyType ( 42 ) ; | How to efficiently implement immutable types |
C# | What algorithm can I use to find the set of all positive integer values of n1 , n2 , ... , n7 for which the the following inequalities holds true.For example one set n1= 2 , n2 = n3 = ... = n7 =0 makes the inequality true . How do I find out all other set of values ? The similar question has been posted in M.SE.ADDED :... | 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 2n7 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 3n7 + 205 > 0n1 > = 0 , n2 > = 0 , n3 > =0 . n4 > =0 , n5 > =0 , n6 > =0 , n7 > = 0 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 6n7 + 2n8 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 7 - 3n8 + 205 > 0n1 > = 0 , n2 > =... | find the set of integers for which two linear equalities holds true |
C# | In deferred ( with impoersonate = no ) to send the Value to the WIX to CA , i am using set property and valueand collecting the data in CA using session.CustomActionData [ `` key '' ] ; Is there any way to send back the data to the WIX from CAIn immediate i was using , ... how to achieve this in deferred CA | < Property Id= '' RESTART '' Secure= '' yes '' Value= '' false '' / > session [ `` RESTART '' ] = `` true '' | Wix Custom action set value from CA to wix |
C# | I 'm trying to make a List < byte > from a file that contains string ( Hexadecimal ) .the definition is : if I want to add my information directly I use something like this : Note : Without any quotation or double-quotation .The problem is when I want to do the same thing from file ! Now I want to know what 0xb8 's typ... | List < byte > myArray = new List < byte > ( ) ; myArray.Add ( 0xb8 ) ; 0xc3.GetType ( ) .ToString ( ) Line = `` 0xb8 '' ; myArray.Add ( Convert.ToInt32 ( Line ) ) ; Argument 1 : can not convert from 'int ' to 'byte ' | Add hexadecimal from file to List < byte > |
C# | Is there a way to unwrap the IObservable < Task < T > > into IObservable < T > keeping the same order of events , like this ? Let 's say I have a desktop application that consumes a stream of messages , some of which require heavy post-processing : I imagine two ways of dealing with that.First , I can subscribe to stre... | Tasks : -- -- a -- -- -- -b -- c -- -- -- -- -- d -- -- -- e -- -f -- -- > Values : -- -- -- -A -- -- -- -- -- -B -- C -- -- -- D -- -- -E -- -F -- > IObservable < Message > streamOfMessages = ... ; IObservable < Task < Result > > streamOfTasks = streamOfMessages .Select ( async msg = > await PostprocessAsync ( msg ) )... | Unwrapping IObservable < Task < T > > into IObservable < T > with order preservation |
C# | I do n't know if that 's been asked before , but I have n't been able to find an answer , nonetheless . My question is this ; in For loops , this is acceptable.But this is NOT : Why is it that I can not use '== ' to determine whether the condition has been met ? I mean , both expressions return true or false depending ... | int k = 0 ; for ( int i = 0 ; i < = 10 ; i++ ) k++ ; int k = 0 ; for ( int i = 0 ; i == 10 ; i++ ) k++ ; int k = 10 ; if ( k == 10 ) { // Do stuff . } | Why is it that I ca n't use == in a For loop ? |
C# | I 've recently encountered an error `` ObjectDisposedException : Can not access a closed Stream '' when using code following the format : So the exception is caused because the Dispose of the TextWriter Disposes the Stream ( hashStream ) that is wrapped . My questions are thus : Does this convention applied ( with defa... | [ ObjectDisposedException : Can not access a closed Stream . ] System.IO.MemoryStream.Write ( Byte [ ] buffer , Int32 offset , Int32 count ) +10184402 System.Security.Cryptography.CryptoStream.FlushFinalBlock ( ) +114 System.Security.Cryptography.CryptoStream.Dispose ( Boolean disposing ) +48 using ( var stream = new M... | Who owns wrapped streams ( e.g . TextWriter ) in .NET ? |
C# | I 've started reading Jon Skeet 's early access version of his book , which contains sections on C # 4.0 , and one thing struck me . Unfortunately I do n't have Visual Studio 2010 available so I thought I 'd just ask here instead and see if anyone knew the answer.If I have the following code , a mixture of existing cod... | public void SomeMethod ( Int32 x , Int32 y ) { ... } public void SomeMethod ( Int32 x , Int32 y , Int32 z = 0 ) { ... } SomeClass sc = new SomeClass ( ) ; sc.SomeMethod ( 15 , 23 ) ; | Does C # 4.0 and a combination of optional parameters and overloads give you a warning about ambiguity ? |
C# | Okay here we go : Stream.html ( Template file ) Default.aspx ( jQuery ) Update : The above has been changed to : Issues with jQuery : I have comments that belong to each .streamItem . My previous solution was to use ListView control as follows : So as you can see , this is not a solution since I started using jQuery Te... | < div class= '' streamItem clearfix '' > < input type= '' button '' / > < div class= '' clientStrip '' > < img src= '' '' alt= '' $ { Sender } '' / > < /div > < div class= '' clientView '' > < a href= '' # '' class= '' clientName '' > $ { Sender } < /a > < p > $ { Value } < /p > < p > $ { DateTime } < /p > < div class=... | CSS + jQuery - Unable to perform .toggle ( ) and repeated jQueryTemplate Item [ I must warn you this is a bit overwhelming ] |
C# | I am seeing this strange issue , and ca n't find anything similar to this anywhere on the web : I tried this in various C # projects and even asked another developer to confirm the behaviour is identical in a different project on a different machine . I tried the same in VB.NET : Am I loosing it ? | int l = `` K '' .Length ; //This actually returns 2 ! ! ! The 'Autos ' window in //the debugger also shows `` K '' .Length as 2.string s = `` K '' ; l = s.Length ; //Whereas this returns 1 as expected Dim l As Integer = `` K '' .Length 'This returns 1 correctly | Why `` K '' .Length gives me wrong result ? |
C# | I have a method SaveChanges < T > ( T object ) that is frequently called throughout my code , except depending on the action calling the method , there would be a different method called from within SaveChanges . Something like this ... Usage Examples : I 've read up on delegate methods but I 'm a little confused as to... | protected void SaveChanges < T > ( T mlaObject , SomeFunction ( arg ) ) where T : WebObject { try { this._db.SaveChanges ( ) ; } catch ( Exception e ) { Console.WriteLine ( `` Error : `` + e ) ; SomeFunction ( arg ) ; } } SaveChanges < MlaArticle > ( article , article.Authors.Remove ( person ) ) //person is an object o... | Passing a method as an argument |
C# | I 'm calling a third-party API which has a method that looks like this : My challenge is , I have to call Discover because it does some work under-the-covers that I need . At the same time , I have to wait for Discover to complete before running my custom code . To further complicate matters , I ca n't just put my code... | myServiceClient.Discover ( key , OnCompletionCallback ) ; public bool OnCompletionCallback ( string response ) { // my code } Func < SystemTask > myFunction = async ( ) = > { await myServiceClient.Discover ( key ) ; // my code } | Awaiting a Callback method |
C# | I have a C # project working with input audio Stream from Kinect 1 , Kinect 2 , Microphone or anything else.The buffer variable is a Stream from component A that will be processed by a SpeechRecognition component B working on Streams.I will add new components C , D , E , working on Streams to compute pitch , detect sou... | waveIn.DataAvailable += ( object sender , WaveInEventArgs e ) = > { lock ( buffer ) { var pos = buffer.Position ; buffer.Write ( e.Buffer , 0 , e.BytesRecorded ) ; buffer.Position = pos ; } } ; var MultiStream buffer = new MultiStream ( ) ... SendMyEventWith ( buffer ) public void HandleMyEvent ( MultiStream buffer ) {... | How can I split and pipe multiple NAudio stream |
C# | Trying to construct nameof expression from scratch using C # SyntaxFactory . Roslyn fails to recognize my InvocationExpressionSyntax as a contextual nameof keyword and throws error diagnostics upon Emit command.Tried to give Roslyn valid code to parse in hope that I 'll find differences between my syntax construct and ... | var CODE = `` class X { void Q ( ) { var q = nameof ( Q ) ; } } '' ; var correctSyntaxTree = CSharpSyntaxTree.ParseText ( CODE ) ; var correctRoot = correctSyntaxTree.GetRoot ( ) ; var correctNameOf = correctRoot.DescendantNodes ( ) .OfType < InvocationExpressionSyntax > ( ) .First ( ) ; var correctExpression = ( Ident... | Constructing NameOf expression via SyntaxFactory ( Roslyn ) |
C# | I saw thisbut I also saw thisWhat 's the difference ? | i > = 5 i = > 5 | What is the difference between > = and = > ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.