Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] C# Object Properties

Started by GenuineXP Apr 26, 2006 at 3:58 PM 22 replies 2.7k views
Original Post
GenuineXP
GenuineXP
Hello. I was just wondering about properties in C#. I thought I'd try to move my game engine project from C++ to C# and use the Tao Framework to gain access to SDL, OpenGL, and OpenAL (which the C++ project uses). I've started constructing my classes and just love properties and interfaces in C#! My question is, do I always need to create a complimentary variable for each property I build into a class? Sometimes I just don't have to, and the value I'm searching for within the get{} statement can be calculated on the fly, but most of the time (whenever a set{} statement is involved, for instance) my classes have private members that the properties access. I know this is pretty normal, but conflicting identifiers are really annoying me. What's the common practice or naming convenction? I like to name variables with capital words, such as FramesPerRow or DynamicWeebulFluxCapacitor. I like the same convention for properties too though. It seems that normally member variables are started with a lowercase word followed by uppercase words, such as framesPerRow or dynamicWeebulFluxCapacitor. How should I go about doing this? I know it's a simple little question, but I thought I'd ask. :-) Thanks!
RenderTarget
RenderTarget
Firstly, no, properties don't strictly need a field behind them. But make absolutely sure about how you're using properties that compute things. It's tempting to use them like fields, but if they compute on the fly, they'll obviously be much slower. At that point, use a method so you're always aware of the potential cost.

As for naming, I tend to use m_ prefixes for fields, but that (hungarian) is going out of style pretty quickly. Fields marked public generally don't use m_ though; they're big camel case, like you do.
[sub]My spoon is too big.[/sub]
GenuineXP
GenuineXP
Yeah, I'm used to using the m_ prefix as well; that's how all of my non-public members are named in the C++ project. I was tempted to do the same here, but I haven't seen it done in any of the C# examples, libraries, and programs I've looked at.
RenderTarget
RenderTarget
Lots of people spew vitriol about hungarian notation of any kind, and I can see their point. I still use them though, partially due to habit.
[sub]My spoon is too big.[/sub]
tanakas
tanakas
Computation of Accessors ('Get' Properties) also occurs in the debugger when you have a watch on a variable. In general, it's a bad idea to calculate values in accessors (or in mutators for that matter.) You should use the mutators for value checking only if you can help it. Visual Studio 2k5 is much better about this than 2k3 was. But it's something to be aware of.

// C# Codeusing System;namespace AccessorTest{    class A    {        private int _value;        public int Value        {            get            {                Console.WriteLine("Value was calculated...");                return _value * 10;            }            set            {                Console.WriteLine("Value was set...");                _value = value;            }        }    }	/// <summary>	/// Summary description for Class1.	/// </summary>	class Class1	{		/// <summary>		/// The main entry point for the application.		/// </summary>		[STAThread]		static void Main(string[] args)		{			A a = new A();            a.Value = 1;            Console.WriteLine("a's value is: {0}", a.Value);            Console.WriteLine ( "Put a break point here...");            Console.WriteLine ( "Add a watch for the a object and expand...");            Console.WriteLine ( "Try messing around with the _value and Value entries...");            a.Value = a.Value + 3;		}	}}
Wyzfen
Wyzfen
i use m_ for my private variables - because thats what i used at work.
After a quick search, it seems that even within microsoft theres argument - some say dont use anything, some say use _'s before, they all agree, drop the m :p
so;

int myVariable;public int MyVariable{   get   {        return myVariable;   }}


or ...

int _myVariable;public int MyVariable{   get   {        return _myVariable;   }}


Since C# -can- tell the difference in both cases between the property and the variable, you could use either. It sounds like good idea to use the same name for members and properties though - especially as VS 2005's code snippets tools does it that way.
On the other hand, Visual Basic is case-insensitive - which is why people suggest the second option for both VB.NET and C#, for consistency.

I've also heard the argument that people only used the m_ instead of _ in the first place because C++ doesnt allow variable names to start with a _

Overall, I think i'll stick with _ - one i can wean myself off of m_. just because i like to be able to know which are members and which are locals - without having to use this.myVariable :p

Hope that gives you something to think on

- Wyzfen
GenuineXP
GenuineXP
I'll try prefixing private fields with _ for this project and see how it feels. The little 'm' does seem a bit awkward.

Thanks for all of the replies! I appreciate the input. :-) Any more comments are very welcome.
TheTroll
TheTroll
I try to prefix my private members with the type. str_ for string, i_ int, s_ for shor and b_ for bool and so on. This just gives you a remember of the type whne you are using them. A very old habit from C programming.

theTroll
nagromo
nagromo
I think there's a difference between mWellNamedMemberVariable and iInteger. Prefixing member variables with m prevents name conflicts and tells me scope.

Some of my C# code has stuff like mIsFullscreen as a private member variable and IsFullscreen as a property that automatically changes the screenmode when it's changed.
xeddiex
xeddiex
Quote:
Original post by TheTroll
I try to prefix my private members with the type. str_ for string, i_ int, s_ for shor and b_ for bool and so on. This just gives you a remember of the type whne you are using them. A very old habit from C programming.

theTroll


The down side is that later on in your project if you changed the type, you could forget to update the variable prefix. [grin]

I personally like making a property for every field in my class. The reason is that if say, you have a simple field typed: int age, that simply retrievs and sets an age, and, if later on you wanted to add some extra lines of inside-class computational code to age, you would have to make it a property or so. If you had made it a property in the beginging, it would have saved you a bit of typing. But anyways, simplistic properties are usually optimized by making them a direct set and get (avoiding the property).

- xeddiex
one..
BeanDog
BeanDog
Wow, this topic has gone away from its original purpose, but I'll bite.

I use m_ for all non-public member variables in all my classes, plus an additional letter identifier for native types and arrays:
public class MyClass{  private class MySubClass  {    public int Size;  //no prefixes for public members    public bool Visible;  }  private int m_iSize;  private bool m_bVisible;  private MySubClass m_Item;  private MySubClass [] m_aItems;  public int Size  {    get { return(m_iSize); }    set { m_iSize = value; }  }}
jfclavette
jfclavette
In C++ I use _member, in C# I use memberVariable and MemberVariable for the property
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Bob Janova
Bob Janova
I use a lower case first letter for fields (unless they're public) – I think this is camel casing? – and capitalise each word for properties. I.e.
int id;DateTime lastAccess;public int ID { ... }public DateTime LastAccess { ... }
Alpha_ProgDes
Alpha_ProgDes
you all really don't do:
public class Example {   private int aValue;   public int AValue {      get {         return aValue;      }      set {         aValue = value;      }   }

do you?

but other than that, properties are cool. much better than get/set functions.
Beginner in Game Development?  Read here. And read here.  
Bob Janova
Bob Janova
Occasionally, yes. (There's a big argument about this right now in Game Programming, actually.) More common, though, would be a simple read-only property (very handy!) or something like this:
int something;public int Something { get { return something;} set {  // bounds check value  something = value;  // inform various other pieces of code that 'something'  // has changed }}
GenuineXP
GenuineXP
Thanks for all of the input. This discussion has been insightful. :-)

I've started by prefixing all of my non-public member variabled with '_'. I have to admit, it looks a bit messy sometimes, but it does make it easy to distinguish between private/protected fields and public ones. In either case, it's only the properties that have to look pretty in the end since those are what you and your users are gonna see, right? :-)

I wish there was a way for fields and properties to share the same name, but I guess the compiler would have trouble figuring out which one you're accessing, especially from within the class itself where non-public fields can be accessed. Changing the syntax of properties would be no good either; they're awesome just as they are.

Thanks again.
Talonius
Talonius
We use m_ as a prefix for our member variables. I don't consider it to be "Hungarian" notation, and I prefer the m_ to simple _ because it is more informative, relatively speaking.

CamelCase for properties, pascalCase for parameters and local variable names.

Your code shouldn't get too messy though - the normal place to access the member variables would be the properties; if possible, throughout the rest of the code, you should access the variable through the property. (Exception being if the access isn't granted that you need on the property. In .NET 2.0 you can specify access levels for the get and set individually though so even there, it's not a huge problem.)

..what we do will echo throughout eternity..
Enselic
Enselic
I think any form of Hungarian notation only messes up the code, including the _-prefix. This is what a typical class of mine looks like:
class GameClass{    public GameClass(int valueOne, float valueTwo)    {        this.valueOne = valueOne;        this.valueTwo = valueTwo;    }    public void SomeMethod(float paramOne, bool paramTwo)    {        valueOne = 2 * paramOne;        // ...    }    // I use properties for read-only members    public int ValueOne    {        get { return valueOne; }    }    // I use public acces for read/write members (unless something needs    // to be done within the getter/setter).    public bool ProgramCrash;    private int valueOne;    private float valueTwo;}

No prefixes, and still no clashes. Code looks good, and still works good [smile].
Wyzfen
Wyzfen
hmm. the this's arent as annoying as i thought they'd be - you've convinced me Enselic.
now to do a search / replace of m_ for this.

wish it was that easy :p
Nypyren
Nypyren
I use mostly the same convention that Enselic does (constructor parameter 'this' trick and all). It works very well and I've never gotten confused or forgotten which variables are locals, parameters or members.

The only difference is that I leave public member variables lowercased instead of capitalizing them like he does.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.