Skip to content

Classes with methods and properties

NN--- edited this page Apr 11, 2012 · 5 revisions

Classes with methods and properties

  • Category: Defining Types
  • Description: Classes can contain methods of general form and properties.
  • Code:
using System;
using System.Console;
using System.Diagnostics;
using Nemerle.Assertions;

// The macro "Record" creates a constructor which initializes all instance 
// fields of the class. In this case the auto-property field.
[Record] 
class Circle2
{
  public Radius : double { get; set; } // auto property Read/Write with get and set

  // Read only property with get
  public Area : double { get { Math.PI * Radius * Radius } }

  public this() { this(1.0) }

  public this([NotNull] text : string) { this(double.Parse(text)) }

  public CalculateCircumference() : double { System.Math.PI * 2.0 * Radius }

  public override ToString() : string {$"Circle = $Radius"}
}

    def c1 = Circle2(2.0);
    def c2 = Circle2("10,0");
    def c3 = Circle2();
    
    WriteLine($"c1.Area = $(c1.Area) = $c1");
    WriteLine($"c2.Area = $(c2.Area) = $c2");
    WriteLine($"c3.Area = $(c3.Area) = $c3");
    c1.Radius = 5.0;
    c2.Radius *= 10;
    WriteLine($"c1.Area = $(c1.Area) = $c1");
    WriteLine($"c2.Area = $(c2.Area) = $c2");
    
    def circumference = c1.CalculateCircumference();
    WriteLine($"circumference $circumference");
  • Execution Result:
c1.Area = 12,5663706143592 = Circle = 2
c2.Area = 314,159265358979 = Circle = 10
c3.Area = 3,14159265358979 = Circle = 1
c1.Area = 78,5398163397448 = Circle = 5
c2.Area = 31415,9265358979 = Circle = 100
circumference 31,4159265358979


[Copyright ©](Terms of use, legal notice)

Clone this wiki locally