.net,f#,immutability , What is the difference between member val and member this in F#?


What is the difference between member val and member this in F#?

Question:

Tag: .net,f#,immutability

When I created a class containing a generic, mutable .NET Stack in F# like the example below, that stack ignores anything I push onto it.

open System.Collections.Generic

type Interp(code: int array) =
    member val PC = 0 with get, set
    member this.stack: Stack<int> = new Stack<int>() 
    member this.Code = code

let interp = Interp([|1;2;3|])
interp.stack.Push(1)
printfn "%A" interp.stack // prints "seq[]" WAT?!

Yet if I make the stack mutable via a property:

open System.Collections.Generic

type Interp(code: int array) =
    member val PC = 0 with get, set
    member val stack: Stack<int> = new Stack<int>() with get, set 
    member this.Code = code

let interp = Interp([|1;2;3|])
interp.stack.Push(1)
printfn "%A" interp.stack // prints "seq[1]"

Everything magically works like I'd expect.

What on earth is going on here? My understanding of immutability from previous languages (C# mostly) would say that even though the stack in the first example is an immutable member, that immutablity should only go as far the reference (aka I shouldn't be able to reassign Stack itself). I should still be able to push values to/from it. What am I missing, and if trying to mutate that stack is the wrong thing, why doesn't it throw an exception or a compile error?


Answer:

If you try to compile the first version, and then use e.g. Reflector to decompile it to C#, you'll see that the stack member is defined like this:

public class Interp
{
    public Stack<int> stack
    {
        get { return new Stack<int>(); }
    }

    // Other members omitted for clarity...
}

As you can see, this is also valid C# code, but obviously not what you want.

The second version cross-compiles to something like this:

public class Interp
{
    internal int[] code;
    internal Stack<int> [email protected];

    public Interp(int[] code) : this()
    {
        this.code = code;
        [email protected] = new Stack<int>();
    }

    public Stack<int> stack
    {
        get { return [email protected]; }
        set { [email protected] = value; }
    }

    // Other members omitted for clarity...
}

This seems more like what you'd want a property to do.


Related:


Foreign key not updating in entity frame work


c#,.net,entity-framework,foreign-keys
I have a class like public class Document { [Key] public int Id { get; set; } public User ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } } Here “User” is a class with some properties (all are primitive types ) Here is my mapping of...

How can I resolve the “Could not fix timestamps in …” “…Error: The requested feature is not implemented.”


linux,build,f#
I have been trying to build a project in F# on Linux that I have located here on github. It's a basic kata project that I am working on as a demo. However on Linux (specifically Ubuntu 14.04 LTS Desktop) I haven't been able to get it to build yet...

How can I determine if an object of anonymous type is empty?


c#,.net
I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

OpenXml.WordProcessing.Justification always comes as OpenXmlUnknownElement


.net,ms-office,openxml,openxml-sdk
I'm building a table using OpenXml and setting the Justification property for every cell. It doesn't really matter where I assign this property, either in the Run element or as a TableCellProperty, when the document is open using the Productivity Tool for MS Office the Justification element always comes as...

Visual Studio Assembly force-installs Target Framework


c#,.net,visual-studio-2013,.net-framework-version
I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

Does MongoDB successful insert guarantee populated ID's?


c#,.net,mongodb-csharp,mongodb-csharp-2.0
We are using the MongoDB C# driver to insert a collection of records using InsertManyAsync. We currently have code that iterates the entire collection after InsertManyAsync returns, confirming that the ID's are populated. I would expect that the driver takes care of this already, but I have not found documentation...

Related entity not loaded


c#,.net,entity-framework
I'm starting a new entity framework project and I'm defining relations among entities. I defined this simple entities: [Table("db_owner.Students")] public partial class User { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public int? SchoolClassId { get; set; } [ForeignKey("SchoolClassId")] public...

Where to store an mp4 file in my project?


.net,vb.net,visual-studio,mp4
I have been studying vb.net for a couple of months now and I want to try something new. I have this sample project to try. It is a web browser and I want that if a button will be clicked, a video will play immediately. This is what my application...

How does the Take() method work in LINQ


c#,.net,linq,entity-framework
I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

F# Discriminated Union - “downcasting” to subtype


f#,discriminated-union
I don't really know what the proper title for this question should be, but: I have a discriminated union called MyDiscriminatedUnion in F#: type MyDiscriminatedUnion = | Foo of Foo | Bar of Bar where Foo and Bar are record types: type Foo = { ... } type Bar =...

inconsistent timing from .net StopWatch


c#,.net,timing,stopwatch,cudafy.net
I have a C# & .NET application that uses a GPU (NVIDA GTX980) to do image processing. There are 4 stages and I synch the CPU to the GPU (no overlap in time) to do timing. But the numbers do not add up. Launch() will do a async launch of...

QUERY IN C# ,where statement


c#,.net,select
How can I write this query on c# : SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=combobox1.text; ...

Custom drawing using System.Windows.Forms.BorderStyle?


c#,.net,vb.net,winforms,custom-controls
I want to mimick drawing of default border based on value of property BorderStyle. Instead of single border around the control, my control is visualised as four adjacent custom-drawn boxes (2×2), each having standard border drawn individually. So for example, if Control.Border is set to FixedSingle value I want to...

Capturing group recursively inside non-capturing group?


.net,regex
So I've got the following input: 1,6-10,10000,2,10-11 And the following regex: ^\d+(?:,(\d+|\d+-\d+))*$ in the .NET Regex I want to match each of the groups between the commas but I also want the capturing groups to end up like the following: Group 1: 1 Group 2: 6-10 Group 3: 10000 Group...

DialogBox with value verifications


c#,.net,winforms
For my application which deals with graphics, I've made a little DialogBox to set: Max; Min; Major Step (of the scale); Minor Step. Here's a screen capture: I want to validate a few things before allowing the user to click Ok: Max >= Min MaxScale >= MinScale. But it's not...

Dependency Injection for concrete .Net classes


c#,.net,dependency-injection,ninject
What is the preferred way for injecting/isolating classes that are sealed in dlls and do not implement interfaces? We use Ninject. Let's say that we have a class "Server" and we want to inject/isolate the class TcpServer which "Server" uses. Don't want to be too specific because I want to...

Application is missing required files


c#,.net,windows,winforms,sharpdevelop
Pic of Error: http://s23.postimg.org/7uj6qcxtn/9708083373e57a9ec91e4296e302f88e.png Cannot Download the Application. The Application is missing required Files. Contact Application Vendor For Assistance. So I'm building a windows form application using SharpDevelop 5.2 and I'm trying to make a standalone/version someone else would be able to use on another machine. In sharpdevelop (and visual...

F# Custom operators


f#,operator-overloading
I've defined a custom operator in F# like this: static member (&?) value defaultValue = if value = null then defaultValue else value The operator is defined within a type and should be called in the following scenario: I'm retrieving information about the system processors using WMI. Now i want...

SpecFlow Ambiguity in bindings


c#,.net,bdd,specflow
I'm working with Spec-flow for quite some days. I am facing "Multiple matching found.Navigating to first match", while Debugging this can be solved, but when I'm running the entire solution Its failing because of Ambiguity in bindings. I'm running around 4 C sharp class files in a Single project Feature:...

How to handle Arithmetic operation OverflowException in F#?


python,f#
I'm doing Project Euler problem 1 in F#: Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples...

Is this definition of a tail recursive fibonacci function tail-recursive?


scala,f#,functional-programming,tail-recursion,continuation-passing
I've seen around the following F# definition of a continuation-passing-style fibonacci function, that I always assumed to be tail recursive: let fib k = let rec fib' k cont = match k with | 0 | 1 -> cont 1 | k -> fib' (k-1) (fun a -> fib' (k-2)...

Automapper AfterMap function initialising classes


.net,vb.net,automapper
Can anyone please explain how does the AfterMap function initalises the class objects passed in the lambda expression? When i run this bit of code as myself, it populates the dest object with my details. i can't figure out how is it doing that? but if someone can tell me...

Unhandled exceptions and background workers


.net,exception-handling,backgroundworker
In our application we use several background workers which are executed using SERVICENAME__bgw.RunWorkerAsync() where SERVICENAME is one of several different background worker processes executed by different timers. We recently saw this error message that was shown after an unhandled error bubbled up to the top of the call stack: My...

XElement.Value is stripping XML tags from content


c#,.net,xml,xml-parsing,xelement
I have the following XML: <Message> <Identification>c387e36a-0d79-405a-745c-7fc3e1aa8160</Identification> <SerializedContent> {"Identification":"81d090ca-b913-4f15-854d-059055cc49ff","LogType":0,"LogContent":"{\"EntitiesChanges\":\" <audit> <username>acfc</username> <date>2015-06-04T15:15:34.7979485-03:00</date> <entities> <entity> <properties> <property> <name>DepId</name> <current>2</current> </property>...

Programmatically accessing TFS history [closed]


c#,.net,powershell,tfs
I have a solution under TFS source control and had written some sample code using an external library that was deleted a few months ago. I am certain that the code was checked in before that class file was deleted. I am able to manually browse to previous versions of...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)


c#,.net,windows,sendkeys
I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

how can I add a column to IQueryable object and modify its values


c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

How to rewrite this C# code


f#
I have this C# code: const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = stream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } I need to rewrite it in F#. I can do it like this: let bufferLen : int =...

I want to upload video on youtube using client side login. without open web page permission


c#,.net,google-api,youtube-api,google-api-dotnet-client
When I upload video to YouTube using client side login. The first time redirect to UI for permissions. I want upload without redirect to web page. I need to execute this code on server. Here is my code. private async Task<string> Run(string title, string description, string filepath) { var videoID...

Consuming and exposing webservices in one project (.NET)


.net,web-services,rest,soap
What is best practice concerning consuming and exposing webservices in one project? (.net) I need to create a rest webservice to expose data. The rest webservice would need to consume this data from another (SOAP) webservice from a third party. (The data needs to be merged with data present in...

Why when trying to upload a video file to youtube i'm getting InvalidCredentialsException?


c#,.net,youtube,youtube-api,google-client-login
This is my code in form1: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace YouTube_Manager { public partial class Form1 : Form { YouTubeRequestSettings settings; YouTubeRequest request; string username...

ASP.NET MVC posting list from view to controller


c#,.net,asp.net-mvc,razor
I have a view model in my ASP.NET MVC application: public class FiltersViewModel { public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu public IList<TechnologyFilter> TechnologyFilters { get; set; } public IList<ContractTypeFilter> ContractTypeFilters { get; set; } public FiltersViewModel() { this.TechnologyFilters = new List<TechnologyFilter>(); this.ContractTypeFilters =...

Web API - Set each thread with the HttpRequestMessage id?


c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

MySQL database to combo box using mysqldatareader in c#.net [closed]


c#,mysql,sql,.net
MySQL database to combo box using mysqldatareader in c#.net MySqlCommand cmd = new MySqlCommand("select * from product", connection); MySqlDataReader dread = cmd.ExecuteReader(); while (dread.Read()) { } using mysqldatareader not a mysqldataadapter....

Feature-specific compatibility of a .NET 4.5 application on a system with .NET 4.0


c#,.net,zipfile
I have a project which runs fine on 4.0, however in the interests of utilizing the new ZipFile class I have decided to target 4.5. The vast majority of my users will have 4.5+ installed, but its not impossible someone with only 4.0 may come along and try to use...

Regex to remove `.` from a sub-string enclosed in square brackets


c#,.net,regex,string,replace
I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

Is Serialization the same as GetBytes?


.net
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes. Found this on google. I use .Net to send packets using a socket connection. I use Encoding.Default.GetBytes(). Serialization is confusing, what is the difference of it to GetBytes?...

Set default value for string prompt


c#,.net,autocad,autocad-plugin
The editor class has a method called GetString which prompts the user for a string value via AutoCAD's command prompt. I call it in this wrapper method: public static string PromptUserForString(string message = "Enter a string: ", string defaultAnswer = "") { return _editor.GetString("\n" + message).StringResult; } The argument message...

Asynchronously manipulating data from streamReader in F#


asynchronous,f#,streamreader
On the line of Read large txt file multithreaded?, I have the doubt of whether it is equivalent to pass to each thread an sliced chunk of a Seq and whether it will safely handle the paralellism; is it StreamReader thread-safe? Here is the code I am using to test...

How can i get list of my youtube videos from youtube?


c#,.net,winforms,youtube,youtube-api
I installed the google api 3 and the OAuth2. And i tried the google develope example: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace Youtube_Manager { public partial class...

Formatting large numbers in C#


c#,.net,unity3d,formatting
I am using Unity to make an "Incremental Game" also known as an "Idle Game" and I am trying to format large numbers. For example, when gold gets to say 1000 or more, it will display as Gold: 1k instead of Gold: 1000. using UnityEngine; using System.Collections; public class Click...

Listing directories by content size using C# [closed]


c#,.net,windows,linq
I'm trying to list all folders of my c drive excluding the document folder which i do not seem to have access to. This first seemed rather simple to me but i found myself still struggling with it despite the seemingly rich .net library. I can't post any code as...

Unconstrained type parameters casting


c#,.net,types,casting
My situation: interface ISomeInterface { void DoSmth<T>(T other); } class Base : ISomeInterface { public virtual void DoSmth<T>(T other){ // for example do nothing } } class Derived<T2> : Base { Action<T2> MyAction {get;set;} public override void DoSmth<T>(T other){ if(typeof(T2).IsAssignableFrom(typeof(T))) MyAction((T2) other); } } This gives me an error: Cannot...

How does convert.ToString(C0) behave?


c#,.net
I have different scenarios. I need output where the value must return comma separated values in ₹ format which it does in my system where I have the ₹ rupee symbol. Whereas in the user system C0 returns $ value with comma separated values I do not know if he...

External Datepicker not working


javascript,jquery,.net
I'm working with an external jss library that will let me use a datepicker that doesn't cut off the previous and next months dates. I'm getting an error when going through the coding. code $.fn.calendar = function (options) { var _this = this; var opts = $.extend({}, $.fn.calendar.defaults, options); var...

Microsoft Band and WPF


.net,wpf,dll,microsoft-band,.net-core
I have downloaded the sample code for Band SDK for Windows. Then I added a new WPF project and grabbed the latest SDK through Nuget (Version 1.3.10518.1). Now under packages\Microsoft.Band.1.3.10518\lib, the following folders are contained: netcore451 portable-net45+win+wpa81 portable-win81+wpa81 wpa81 Now as I need .NET 4.5 support I have referenced the...

String Format: How to add any number of zeros before string


c#,.net
I'd like to have strings that have zeros before them. I use this code: string a = string.Format("{0:00}",7); The above code gives a two digits string, but what if I want a n digit string? Let's say n = 5, how can I use string.format to get something like 0004?...

Catch concurrency exception in EF6 to change message to be more user friendly


c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Best approach to upgrade MVC3 web app to MVC5?


c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

Move windows form from a picturebox in C#


c#,.net,winforms,picturebox
I have a windows form without any border. So i added a picture box and i want the whole form to be moved when that picture box is clicked. public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg,...