various properties of a struct object. - CSharp Custom Type

CSharp examples for Custom Type:struct

Description

various properties of a struct object.

Demo Code

using System;//from www . j a  v a2s  .c  o  m
public interface IDisplayable
{
   string ToString();
}
// A struct can implement an interface.
public struct Test : IDisplayable
{
   private int n;
   private static double d = 20.0;
   // A constructor can be used to initialize the data members of a struct.
   public Test(int n)
   {
      this.n = n;  // A struct can refer to 'this'.
   }
   // A struct may have both object and class (static) properties.
   public int N
   {
      get { return n; }
      set { n = value; }
   }
   public static double D
   {
      get { return d; }
      set { d = value; }
   }
   // A struct may have methods.
   public void ChangeMethod(int newValue, double newValue2)
   {
      n = newValue;
      d = newValue2;
   }
   override public string ToString()
   {
      return string.Format("({0:N}, {1:N})", n, d);
   }
}
public class Program
{
   public static void Main(string[] args)
   {
      Test test = new Test(10); // Invoke a constructor.
      Console.WriteLine("Initial value of test");
      OutputMethod(test);
      ChangeValueMethod(test, 100, 200.0);
      Console.WriteLine("Value of test after calling" + " ChangeValueMethod(100, 200.0)");
      OutputMethod(test);
      ChangeReferenceMethod(ref test, 100, 200.0);
      Console.WriteLine("Value of test after calling" + " ChangeReferenceMethod(100, 200.0)");
      OutputMethod(test);
      test.ChangeMethod(1000, 2000.0);
      Console.WriteLine("Value of test after calling" + " ChangeMethod(1000, 2000.0)");
      OutputMethod(test);
   }
   // ChangeValueMethod - Pass the struct by value.
   public static void ChangeValueMethod(Test t, int newValue, double newValue2)
   {
      t.N = newValue;
      Test.D = newValue2;
   }
   // ChangeReferenceMethod - Pass the struct by reference.
   public static void ChangeReferenceMethod(ref Test t,int newValue, double newValue2)
   {
      t.N = newValue;
      Test.D = newValue2;
   }
   // OutputMethod - Output any object which implements ToString().
   public static void OutputMethod(IDisplayable id)
   {
      Console.WriteLine("id = {0}", id.ToString());
   }
}

Result


Related Tutorials