tags:

views:

215

answers:

6

If I have VB declaration like this Public ReadOnly Property Document() As XmlDocument, what is its C# equivalent? Thanks.

+7  A: 
public XmlDocument Document { get; private set; }

Edit as per comments... Thanks guys, didn't even try to see if it would compile.

thorkia
heh... beat me by one second. :D
Randolpho
Won't compile...
PostMan
C# doesn't support "readonly" declarations like that.
Mehrdad Afshari
@PostMan, Mehrdad, Nescio - fixed, thanks for the comments
thorkia
A: 
public XmlDocument Document { get; private set; }   // For .NET 3.5

For Previous Versions

private XmlDocument _document;
public readonly XmlDocument Document
{
    get
    {
        return _document;
    }
    // You don't need a setter
}
David Basarab
Won't compile: readonly can be used only on fields, not propeties.
itowlson
As in the answer above, `The modifier 'readonly' is not valid for this item`
JMD
+9  A: 

You can use automatic properties in C# 3.0+ to achieve the same thing:

public XmlDocument Document { get; private set; }
Mehrdad Afshari
This is slightly different though: this allows Document to be modified through the property, which the VB version doesn't. (The OP doesn't show the implementation of the VB property, but e.g. this might be a calculated property, or back onto a readonly field.)
itowlson
itowlson: Yes, sure. There's no direct simple translation. You have to manually implement the property in that case.
Mehrdad Afshari
+11  A: 
public XmlDocument Document
{
    get {return someXmlDoc;}
}
Pharabus
thanks for the capitalisation fix
Pharabus
+1  A: 

VB.Net requires you to write read-only, but C# you only need to exclude the setter part of the property.

Wade73
+6  A: 

Here is a great tool that convert automatically VB.NET code to C# and vise versa http://www.developerfusion.com/tools/convert/vb-to-csharp/

martani_net
+1 - teach a man to fish...
Jay Riggs
Rats. I saw this softball lobbed in too late to post a link to this site. +1
Mark Wilkins