.NET Be Forced To Initialize Instance Variables BEFORE Invoking The Base Type Constructor?

Jan 5, 2011

After debugging a particularly tricky issue in VB.NET involving the order in which instance variables are initialized, I discovered that there is a breaking discrepancy between the behavior that I expected from C# and the actual behavior in VB.NET.Nota bene: This question concerns a slight discrepancy in the behaviors of VB.NET and C#. If you're a language bigot that is unable to provide an answer other than "that's why you should use C#, noob", there is nothing for you to see here; kindly move along.Specifically, I expected the behavior outlined by the C# Language Specification (emphasis added):

When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. The variable initializers are executed in the textual order in which they appear in the class declaration.

Contrast that with the portion of the VB.NET Language Specification concerning Instance Constructors, which says (emphasis added): When a constructor's first statement is of the form MyBase.New(...), the constructor implicitly performs the initializations specified by the variable initializers of the instance variables declared in the type. This corresponds to a sequence of assignments that are executed immediately after invoking the direct base type constructor. Such ordering ensures that all base instance variables are initialized by their variable initializers before any statements that have access to the instance are executed.

The discrepancy here is immediately obvious. C# initializes class-level variables before calling the base constructor. VB.NET does exactly the reverse, apparently preferring to call the base constructor before setting the values of instance fields.If you want to see some code, this related question provides a more concrete example of the divergent behavior. Unfortunately, it does not provide any hints as to how one might coerce VB.NET into following the model established by C#.

I'm less interested in why the designers of the two languages chose such divergent approaches than I am in possible workarounds for the problem. Ultimately, my question is as follows: Is there any way that I can write or structure my code in VB.NET to force instance variables to be initialized before the base type's constructor is called, as is the standard behavior in C#?

View 2 Replies


ADVERTISEMENT

C# - Invoking Private / Protected Methods Via Reflection From The Same Object Instance (or Base)

Jan 5, 2012

Is it possible to call a protected method via reflection. I am using this:

Me.GetType.InvokeMember(Stages(CurrentStage),
Reflection.BindingFlags.InvokeMethod,
Nothing,
Me,
Nothing)

Which always calls a method with no params or return. The idea is that the user of my object (transactional processing of business logic) inherits the base class adds in a load of private methods to fire. They then add these method names to a list in the order they would like them fired and the code above will take care of firing them.

It works fine with public methods but not with private or protected methods in the same class (Protected because I have some 'standard' pre built methods to add to the base class). Realistically I could make the methods public and be done with it but my inner nerd wont allow me to do so...

I am assuming this is a security feature. Is there a way to get around this or does anyone have any suggestions on how to proceed but keep my tasty, tasty visibility modifiers in tact?

(NOTE: ITS IN VB.NET but a C# Answer is fine if that is what you are comfortable with).

View 3 Replies

Why Does C# Set Private Variables Before The Base Constructor While .NET Does The Opposite

Mar 3, 2011

comparing C# code and VB.NET and the results between the seemingly identical code were entirely different.(Why C# is always winning over VB.NET?)The explanation given is that C# will initialize the class fields, then call the base constructor, but VB.NET does the exact opposite. Is there a technical reason for the languages to be different? At first glance, it seems that either approach is equally valid, but I can't fathom why they wouldn't have selected the SAME approach.

EDIT: As 'Jeffrey L Whitledge' has pointed out, VB6 did not have inheritance, so I don't think we can say 'to keep VB.NET and VB6 more closely related'.

View 1 Replies

More Specific Type From Base Shared Constructor?

Nov 26, 2010

How do I get using reflection the most generic type from a shared constructor in the base class :

Public Class Foo()
Shared Sub New()
'Here we have code to get the type[code]....

I expect the result to be Bar type and not the Foo. Is it possible?

View 1 Replies

Why Is Constructor Call Valid Only As The First Statement In An Instance Constructor

Nov 2, 2009

what's the rationale behind this limitation: Constructor call is valid only as the first statement in an instance constructor i want to pass an argument to my constructor which validates this argument and calls mybase.new according to this argument but it doesn't let me

example:

Public Class prob
Inherits System.ApplicationException
Public Sub New(ByVal problem As String, ByRef inner_exception As Exception)

[code]....

View 16 Replies

Why It Is Not Necessary To Initialize All Members In Parameterized Constructor Of A Structure

Jan 19, 2012

When it comes to constructors in a Structure type ,it is fact that we can not explicitly provide the default constructor .It is provided by the runtime. Ok, another point that is applicable to C# language is that if we are defining a parametrized constructor then it is compulsory to initialize all fields . We can not leave any field uninitialized , since the runtime will not call default constructor if we are calling parametrized constructor .Its logically right , but in VB.NET language , actually you are free to leave any of the fields uninitialized in your parametrized constructor.

[Code]...

View 9 Replies

Constructor - Whats The Best Way To Initialize Shared Members In A Class In VB.Net?

Dec 8, 2010

I was looking on the interweb to see if there were any good examples on how to initialize shared members within a class while still initializing instance variables. I did find an expression that might fit to the answer:

[code]...

How do I initialize both instance and shared members without re-initializing the shared members every time an object is created from a class? Thanks!

View 2 Replies

.Net OOP Superclass Base.net And Constructor Parameters?

Mar 13, 2009

I have a base class that contains a fairly large number of parameters in it's New constructor. I have 7 subclasses that inherit the Super base class. My question/issue is, all of the subclasses use the same values for most of the parameters in the New constructor of the base class and these subclasses can be called one after the other. I would like to populate the common values for the superclass and then use those for each of the subclasses, but I can't come up with a good way to do this. If I could figure out how to do this, I wouldn't have to pass all of those parameters in the MyBase.New call for each subclass. I'll try to illustrate with some code .

[Code]...

View 3 Replies

C# - Keyword 'this' Not Available Calling The Base Constructor?

Mar 15, 2010

In the inherited class I use the base constructor, but I can't use the class's members calling this base constructor. In this example I have a PicturedLabel that knows its own color and has an image. A TypedLabel : PictureLabel knows its type but uses the base color.

The (base) image that uses TypedLabel should be colored with the (base)color, however, I can't obtain this color

Error: Keyword 'this' is not available in the current context`

[Code]...

View 4 Replies

Why Do Initialize Variables?

Nov 1, 2011

Take a look at this code

[CODE]:....................

View 5 Replies

C# - Need To Initialize New Instance Of Object

Aug 11, 2011

The following code:
CodeVariableDeclarationStatement variableDeclaration = new CodeVariableDeclarationStatement(
// Type of the variable to declare.
typeof(string),
// Name of the variable to declare.
"TestString");

Produces the following VB.Net Statement:
Dim TestString As String

What change would I need to make for it to look like this:
Dim TestString As New StringBuilder()
I'm interested in how to get that NEW keyword to appear.

View 1 Replies

.net - Invoking Interface Method Using System.Object Type Variable

Jan 6, 2011

I have an interface ITest with a method GetResult(). I have a class Test which implements ITest and thereby defines private method GetResult().

Next I create an instance of Test in a different class. The code is as below:

Module NewClass
Public Sub New()
Dim i As ITest = New Test()

[Code]....

I am migrating existing code from VB 6 to VB.NET and hence I'm not supposed to change the access modifier of GetResult. Leaving it Private will throw InvalidCastException Unable to cast object of type 'System.Object' to type 'ITest'

Object type variable o is used in many places and hence I don't want to change that. And yes, Test implements ITest.GetMember with a different name.

View 3 Replies

C# - Initialize The Variables - Name Property Of The Dings Class To Be Initialized At First?

Jan 27, 2011

I have classes similar the following:

[Code]...

I want the Name property of the Dings class to be initialised at first, I know, I could also create the foo-object (as member of dings) later in the constructor. But I want to have it this way, because in the end there are very much singleton objects instantiated in the Dings-class that I want to be created in only one line.

[Code]...

View 3 Replies

Initialize A New Instance Of A Class, But Pass It To Other Forms Too For A Wizard Based App?

Dec 20, 2011

As an ameture developer, I've never really used classes. However, I've been reading about using classes and automatic properties. I have therefore created a class which looks similar to this:

Public Class Quote
Property QuoteNum as integer
Property AccNum as String
Property Price as Decimal
End Class

The stumbling part for me comes in the way of letting form2 know which class form1 has initialized. There are in this example 3 forms to this wizard. If someone starts another wizard whilst half way through the first wizard we need to keep the variables seperate hence using the class. I think I'm along the right track, but maybe confusing myself a little.

[Code]...

View 12 Replies

Naming Convention For Variables In Class Constructor

Nov 26, 2010

In the past when I have written classes and constructors, I named the variables in the constructor parameter something different than what would have been stored in the actual class itself.What I do now is name them the same, and reference the internal variables with Me.varname.Here is a class I just started building.Is my naming convention incorrect? [code]

View 1 Replies

Make Constructor Public And Allow Anybody To Create An Instance Of Class?

Apr 6, 2009

I have a class inside a class.I need to expose the properties of the 2nd class to other classes, therefore it is public.However, I do not wish other classes to be able to create instances of this 2nd class, it should only be instantitated from its parent class.I thought I could resolve this issue by making the constructor of the 2nd class private, but this even prevents the parent class from instantiating its child class! How can I work around this, do I have to make the constructor public and allow anybody to create an instance of the class?

View 3 Replies

VS 2010 - Call Valid Only As First Statement In Instance Constructor

Jul 19, 2011

I'm trying to create an array to be handled during my code. I want to create it as soon as I open the program so I've placed it in my bit of constructor code. This code was working fine before I tried to initialize a new array in there but when I place that in I get the above error message. This occurs whether I put the new array bit of code first in my constructor class or not.

View 5 Replies

VS 2008 Dragdrop - Check If The Present Data Type Inherits From The Base Type

Aug 20, 2009

I have a number of controls (Device1, Device2, etc.) that all inherit from BaseDeviceControl. In the DragEnter event handler I am trying to test for the correct type by using the BaseDevvceControl like this....

[Code]....

View 8 Replies

.net - Get A Base Class Method Return Type To Be The Subclass Type?

Nov 23, 2009

I have a copy function that I'd like to override in subclasses to return the type of the subclass. Here are my interfaces:

Public Interface IBase(Of T)
Function Copy() As T
End Interface

[Code]....

View 4 Replies

Invoke An Instance Function Delegate On An Instance Of A Generic Type?

Aug 4, 2010

D is a dictionary whose entry values are of Type T..What I'm attempting to do is have a delegate like "Serializer" below that I can invoke on an instance of T, such as "Entry.Value" below.Please see the "return Entry..." line below for my wishful thinking.[code]

View 2 Replies

VB Allows The Type Parameters To Be Used As The Base Class For The Generic Type?

Mar 30, 2010

1) VB Allows non-type template parameters2) VB supports explicit specialization 3) VB allows the type parameters to be used as the base class for the generic type4) VB allows a generic type parameter itself to to be a generic 5) VB enforces that all codes are valid for all types of parametrs

View 1 Replies

Creating An Array Of Instances Where Instance Could Be Base Or Sub Class?

Oct 31, 2011

I have a class structure and am attempting to create an array of object instances from the class some instances are parents and some are children Code snippets,

Parent Class object
Option Strict On
Option Explicit On
Public Class cTransportItem

[code]....

View 1 Replies

Casting From Base Type To Derived Type

Jun 29, 2010

I'm wrestling with this treeview control. I have extended the TreeNode class to attach some extra data to the node. Basically, I added one property:[code]Is there a way to cast from a base type to a derived type?

View 11 Replies

Pass A Type To A Constructor For Instantiation?

Mar 7, 2011

What I want to do is pass a Type to another object's constructor, where the other object creates a new instance of Type. I can create a constructor with a parameter declared as System.Type without problem, but when I try to instantiate it tells me there is no such type.

Public Sub New(targettype As System.Type)
Dim Test As System.Windows.Forms.Form = New targettype
End Sub

View 3 Replies

Setting A DataSet Row Value To Nothing Initialize It To The Data Type Minvalue?

Dec 2, 2010

When setting a DataSet row column to Nothing, like row.Date = Nothing, why does it initialize it to the data type minvalue? In this case a date, that gets set to 0000-01-01. The column is set to allow null etc., and if I don't set the row to anything at all, it will leave the column empty. So why does Nothing act this way?

In C# I would've set it to DbNull, I guess, but I'm a tad green on VB.NET - as you might be able to tell. :)

View 2 Replies

Reflection - Passing Values To Constructor Of Type T?

Jun 18, 2012

I have this code to get the default constructor:

Public Function f(ByVal t As System.Type) As Object
Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function

I need to pass values to the Constructor as

Public Function f(ByVal t As System.Type) As Object
Return t.GetConstructor(New System.Type() {someInteger,someString,etc.etc}).Invoke(New Object() {})
End Function

Also I have 3 classes of Type T, with all having different parametric constructor. It's important for me to have it generic as the Classes of type T might increase in future with less or more parameters.

View 1 Replies

XmlSerializer(Type) Constructor Throws ArgumentNullException

Dec 27, 2010

I've been having problems with following code on some computers, while it's worked super on others (most):

Dim xmlSer As New System.Xml.Serialization.XmlSerializer(GetType(XMLContext))
which produces the stacktrace:
System.ArgumentNullException: Value cannot be null.
Parameter name: type
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)

How can that code throw that exception, when the argument is drawn from a gettype call, and note that it doesn't happen when debugging on my own PC, only when it's installed on some of the client PC's???

View 15 Replies

How Variables Declared With Protected Access In A Base Class Are Used To Implement Inheritance

Jul 29, 2010

how variables declared with protected access in a base class are used to implement inheritance.

View 1 Replies

Class - .NET - Automatically Initialize Extended Property Of Type Object?

Feb 15, 2012

I am building a code behind page that has a public property (MyDTOItem) which is essentially a DTO object (dtDTOItem) Note: In my code the Get and Set are actually real code (I stripped it for the example).The problem I am having is in the Page_Load event. When I set the .Member1 property of the DTO object the Get code runs and not the Set and therefore the DTO ibject property .Member1 never gets assigned. I figured out that if I add code (MyDTOItem = New dtDTOItem) to the Page_Load event then it will set the value correctly. What I am trying to figure out is how to initialize the property object without having to do it explicitly. It has to be an extended property because I have custom Get and Set code.

Public Property MyDTOItem As dtDTOItem
Get
End Get
Set(value As dtDTOItem)

[code]....

View 1 Replies

Class - Automatically Initialize Extended Property Of Type Object?

Jun 5, 2006

I am building a code behind page that has a public property (MyDTOItem) which is essentially a DTO object (dtDTOItem) Note: In my code the Get and Set are actually real code (I stripped it for the example).

The problem I am having is in the Page_Load event. When I set the .Member1 property of the DTO object the Get code runs and not the Set and therefore the DTO ibject property .Member1 never gets assigned.

I figured out that if I add code (MyDTOItem = New dtDTOItem) to the Page_Load event then it will set the value correctly. What I am trying to figure out is how to initialize the property object without having to do it explicitly. It has to be an extended property because I have custom Get and Set code.

Public Property MyDTOItem As dtDTOItem
Get
End Get

[code]....

View 10 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved