Question GetType on a private custom type

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
I have a private custom type, how do you do a gettype on it without changing it to public? do i need to declare a gettype inside the class? how do you do that?

VB.NET:
    Private Class customType
        Public Property A As String
        Public Property B As String
        Public Property C As String
        Public Property D As String
        Public Property E As Boolean
    End Class

    Dim XYZ as customType
    Dim ser As New System.Xml.Serialization.XmlSerializer(XYZ.GetType)
 
You'd use theobject.GetType or GetType(typename).
 
The fact that it's Private shouldn't matter. The reason for declaring a type Private is that you only ever want to use it inside the type it's declared in. If you're trying to use it outside its parent type then obviously it shouldn't be Private in the first place. As JohnH has said, there are basically only two ways to get a Type object for a data type: the GetType method that you call on an instance and the GetType statement that you pass a data type. The access level of the data type is irrelevant to that.
 
I did use .gettype in that code but it give me error until I change the type to public

Then you were obviously trying to use it outside its parent type.
 
The only way that you can declare a type Private is if it is declared inside another type. That other type is it is declared inside is its parent type. The only reason that you would declare a type Private is if you intend to use it only within that parent. If you're having an issue with its being Private then you must be trying to use it outside its parent, in which case you shouldn't have declared it Private in the first place. When it comes to types:

Private = only accessible inside its parent (obviously not valid if there is no parent)
Friend = only accessible inside the current project/assembly
Public = accessible anywhere
 
I declared the private class inside the class form1 and called the gettype inside a sub in form1. It returned inaccessible due to its protection level. Only public type can be processed.
 
The problem is not with GetType, the problem is that XmlSerializer can't serialize a private type.
 
OK, I just did a proper test and the issue is not the calling of GetType but the fact that you're trying to pass that Type to an XmlSerializer. The point of declaring a type Private is that it will be used only within its parent type. As far as the world outside the parent type is concerned, the nested type doesn't exist. Serialising an instance breaks that rule. You can call GetType on a Private type without issue. You cannot serialise a Private type. You can't even serialise a Friend type because serialisation is going expose the type beyond the bounds of the assembly that it's declared in. Hence the message that only Public types are accessible.
 
Back
Top