0

I am a beginner programmer looking for some help with c#.

I am writing a program based on a framework and need to create a data member of a class, then initialize the data member to something.

Next,I need to make a property to get and set the data member.

Also, if someone could provide some information on how to typecast the property that would be great.

I'm just looking for examples and general information here. I checked google and only got links from MSDN but did not understand the content.

Thanks!

user3015999
  • 69
  • 1
  • 3
  • 9

2 Answers2

3

Here is a basic explanation, using code:

//Class Definition
public class MyClass
{
   //Data Member with inline initialization
   private int myInt = 1;

   //Standard property
   public int MyIntProp
   {
      get { return myInt; }
      set { myInt = value; }
   }

   //Auto-property, generates the same getter/setter as above with a "hidden" backing property.
   public String MyStringProp {get; set;}

   //Class constructor, great for initialization!
   public MyClass()
   {
       //Set the property to an initial value
       MyStringProp = "Hello World";
   }
}

Typecasting is another monster. You have to be careful when doing it, because very few types can be cast to others. The number types can generally be cast to one another (although you can lose data), and derived types can be cast to their base types, but that is about it.

An example (safe) cast of a number would be:

int myInt = 2;
long myLong = (long)myInt;

That is called a "C-Style" cast (because it's how you do it in C) and is generally how you cast numbers. There are other styles and functions to do the cast of course.

@Iahsrah's suggestion is also a good place to start.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

A basic type is a class which looks like this:

public class MyType 
{

}

You can create a property of this on another class like this:

public class AnotherType 
{
    public MyType InlinePropertyName { get; set; } 

    // Simple propertoes require no implimentation (above), or you can explicitly control it all (below)       

    private MyType _explicitPropertyName;

    public MyType ExplicitPropertyName {
       get {
            return _explicitPropertyName;
       }

       set {
           _explicitPropertyName = value;
       }
    }
}

The you can easily access from elsewhere in your program like this:

var myType = new MyType();
var anotherType = new AnotherType();
anotherType.InlinePropertyName = myType;
shenku
  • 11,969
  • 12
  • 64
  • 118