4

I have this base class that creates a new SQL Server connection and does some utility methods in C#, I want to inherit in F#. Currently I cannot access the protected fields in the C# class from F#, although this would work in C#.

C# abstract class

public abstract class SQL
{
    protected readonly SqlConnectionStringBuilder bld;
    protected readonly SqlCommand cmd;
    protected readonly SqlConnection conn;
    protected readonly string connstring;
    protected string userid;

    public SQL(string server, string db)
    {
        bld = new SqlConnectionStringBuilder();
        bld.DataSource = server;
        bld.InitialCatalog = db;
        bld.IntegratedSecurity = true;
        connstring = bld.ConnectionString;

        conn = new SqlConnection(connstring);
        cmd = new SqlCommand();

        GetUserID();
        //Other utility methods here
    }

F# code to inherit

type Transfer ( server : string ) ( db : string ) = 
inherit SQL(server, db)  
let accessAbstractConn = conn. //Can't access protected field????

Have I missed something here? I have tried aliasing the base class field e.g. this.conn which also does not work.

Thanks Richard

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Richard Todd
  • 2,406
  • 5
  • 32
  • 40

2 Answers2

12

You can add a self-identifier to the constructor:

type Transfer ( server : string, db : string ) as this = 
  inherit SQL(server, db)  
  let accessAbstractConn = this.conn

or, use the base keyword:

type Transfer ( server : string, db : string ) = 
  inherit SQL(server, db)  
  let accessAbstractConn = base.conn
Daniel
  • 47,404
  • 11
  • 101
  • 179
2

See related questions:

Basically I think you can't do it from within a let because it's actually in the context of an implicit lambda.

Community
  • 1
  • 1
sinelaw
  • 16,205
  • 3
  • 49
  • 80
  • Yes it seems so, looking at Daniel's code calling the class with an alias does give access to all members including inherited members. However I cannot access the fields. So how can I change the properties of say, the connection field? – Richard Todd Feb 26 '13 at 15:30
  • @RichardTodd: The two approaches in my answer provide access to _all_ protected members, including fields. – Daniel Feb 26 '13 at 15:33