C # for AS3 developers. Part 3: get, set, sealed, using, const, readonly

Original author: Jackson Dunstan
  • Transfer
  • Tutorial
image

Translation of an article From AS3 to C #, Part 3: AS3 Class Parity

Today we will finish understanding classes in C # (from the point of view of the AS3 developer) and prepare for the next article in which we will be able to get acquainted with concepts that have no analogues in AS3. In the current article, we will consider a way to implement:
- getters / setters (getter / setter)
- functions and classes that cannot be redefined / inherited (final)
- constants
- packages


Get / Set functions

Let's start with getters and setters. To refresh memory, here's what they looked like in AS3:

class Person
{
    private var _name:String;
    public function get name(): String
    {
        return _name;
    }
    public function set name(n:String): void
    {
        _name = n;
    }
}


And here is the equivalent in C #:

class Person
{
    private String _name;
    public String Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }
}


As we can see, in C #, instead of declaring 2 functions, the getter and setter are declared as a single variable. True, this variable does not end with a semicolon (;), but contains a block in the form of curly braces, inside which there are 2 parts: get {} and set {}. These parts are getter and setter functions. Inside the setter, you will have access to the new keyword value, it represents the value that must be set and you do not need to declare it, as you had to do in AS3. If you ignore this difference in syntax, getters and setters work the same in C # and AS3.

C # provides the ability to use an abbreviated notation for such functions, avoiding writing extra code for simple functions:

class Person
{
    public String Name { get; set; }
}


Using this construct will automatically create the _name variable and getter / setter functions, as in the example above. But what if you don't need a setter function? Just remove it:

class Person
{
    public String Name { get; }
}


Most likely, you will need, at a minimum, to allow the Person class to set the values ​​of this variable. For this, the setter can be declared private:

class Person
{
    public String Name { get; private set; }
}


And yet, a bit of C # terminology: class fields that have get and / or set functions (Name) are called “properties”. The variables that are used to store this data (_name) are called “helper fields”.

Final / sealed functions

Now, let's talk about final functions that cannot be overridden (AS3):

class Person
{
    final function print(): void
    {
        trace("I'm a Person");
    }
}
class MyPerson extends Person
{
    // illegal
    override function print(): void
    {
        trace("I'm not just a Person, I'm a MyPerson too");
    }
}


C # provides identical functionality using the word sealed:

class Person
{
    sealed void Print()
    {
        Debug.Log("I'm a Person");
    }
}
class MyPerson extends Person
{
    // illegal
    override void Print()
    {
        Debug.Log("I'm not just a Person, I'm a MyPerson too");
    }
}


Packages and namespace

Packages in AS3:

package com.jacksondunstan.examples
{
    class Person
    {
    }
}


In C #, packages are called namespace, that's all:

namespace com.jacksondunstan.examples
{
    class Person
    {
    }
}


To access the package inside the .as file, you can import the package:

import com.jacksondunstan.examples;
class Printer
{
    function print(person:Person): void
    {
        trace("person has name: " + person.name);
    }
}


In C #, you use the using keyword for namespace:

using com.jacksondunstan.examples;
class Printer
{
    void Print(Person person)
    {
        Debug.Log("person has name: " + person.name);
    }
}


Constants and readonly variables

And finally, let's talk about constants. Here's how a field can be created in AS3 that cannot be changed after the declaration:

class Person
{
    private static const MIN_TEEN_AGE:int = 13;
    private static const MAX_TEEN_AGE:int = 19;
    var age:int;
    function IsTeen(): Boolean
    {
        return age >= MIN_TEEN_AGE && age <= MAX_TEEN_AGE;
    }
}


Here's how to do it in C #:

class Person
{
    private const int MinTeenAge = 13;
    private const int MaxTeenAge = 19;
    int Age;
    bool IsTeen()
    {
        return Age >= MinTeenAge && Age <= MaxTeenAge;
    }
}


An important nuance: in C # for constants, you can use only basic types (for example, int) and strings. This is necessary because such a field will not actually exist, instead, wherever it is used, the values ​​of this field will be substituted. Also, this means that such fields automatically become static (static), and they do not need to be declared as static separately. After compilation, the Person class in C # will look like this:

class Person
{
    int Age;
    bool IsTeen()
    {
        return Age >= 13 && Age <= 19;
    }
}


In AS3, the const keyword was used exclusively for verification at the compilation stage and did not lead to changes / substitutions in the code. If you want to achieve similar behavior in C # or if you need to use a non-basic data type (for example, Person), then you need to use the readonly keyword:

class Person
{
    static readonly Person Newborn = new Person(0);
    readonly int Age;
    Person(int age)
    {
        Age = age;
    }
}


In the example above, there are 2 readonly fields:

1) Newborn - a field that was declared with the static keyword (readonly fields, unlike constants, are not necessarily static). This field will be initialized in the place where it is declared (similar to the constants in AS3).

2) Age - a field that is readonly but not static. It will be initialized in the constructor.

In conclusion, a comparison of the described features of C # and AS3 code:
////////
// C# //
////////
// Collection of classes being used by this file
using org.apache.coolstuff;
// Collection of classes
namespace com.jacksondunstan.examples
{
    class Person
    {
        // Complex getters and setters
        private String _name;
        String Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        // Simple getters and setters
        int Age { get; set; }
        // Read-only field
        readonly int ID;
        // Inlined field
        const int AdultAge = 18;
        // Function that can't be overridden
        sealed void Print()
        {
            Debug.Log("Name: " + name + ", ID: " + ID);
        }
    }
}

/////////
// AS3 //
/////////
// Collection of classes being used by this file
import org.apache.coolstuff;
// Collection of classes
package com.jacksondunstan.examples
{
    class Person
    {
        // Complex getters and setters
        private var _name:String;
        function get name(): String
        {
            return _name;
        }
        function set name(value:String): void
        {
            _name = value;
        }
        // Simple getters and setters
        // {not supported. use complex instead.}
        // Read-only field
        const var ID:int;
        // Inlined field
        // {not supported. use compile-time constants via command-line instead.}
        // Function that can't be overridden
        final function print(): void
        {
            trace("Name: " + name + ", ID: " + ID);
        }
    }
}



In the next article, we will finally begin to consider concepts that have no analogues in AS3.

Do not switch the channel!

Also popular now: