What is a virtual class, attributes and methods?

Asked

Viewed 21,251 times

14

What is a class, attribute and virtual method?

public virtual class nomeclasse { 

    public virtual int id { get;set; }

    public virtual void metodo() { }

}

What difference?

When to use?

3 answers

28


First, in C# it is not possible to use the keyword virtual directly in the class. It is possible to use, yes, abstract to indicate an abstract class.

Also in the world . Net, it is usually called property what you called attribute, being that attribute in . Net means something else... it creates a certain degree of confusion.

From that, we can say that the key word virtual marks the methods and properties that can be extended by a sub-class, i.e., that allows the behavior to be changed through a override. Thus, by creating a subclass, it is possible to make it more specific, but without having to reimplement the whole class, as it is possible to change the behavior punctually.

Example:

public class PessoaBase
{
    public virtual string QuemEVoce()
    {
        return "Não sei quem sou!";
    }
}

public class PessoaMiguel : PessoaBase
{
    public override string QuemEVoce()
    {
        return "Eu sou Miguel!";
    }
}

Note that I extended the class PessoaBase by altering her behavior... in which she replied, "I don’t know who I am!" I altered the behavior in the new class in a way that answers "I am Miguel!".

The most important thing about this is that both classes can be treated the same way, because both are in fact of the type PessoaBase. This means that, through a variable of the type PessoaBase I can operate both an object of the kind PessoaBase as well as one of a kind PessoaMiguel:

List<PessoaBase> pessoas = new List<PessoaBase>
{
    { new PessoaBase() },
    { new PessoaMiguel() },
};

foreach (var pessoa in pessoas)
{
    Console.Write(pessoa.QuemEVoce());
}
  • I wondered when I read, virtual class, I was seeing if it was possible and what would be the behavior, but you already answered. Since it would not make much sense the concept of virtual in a class. +1

  • I think I confused virtual class with partial, rsrsrs also do not know the difference between partial, as for methods, I understood, it was clear, but necessarily needs to be virtual for me to overwrite?

  • @Rod: not necessarily... to give override, the member in the base class must have one of these modifiers: abstract, virtual or override... in the latter case, the base class has already override at the base.

  • It was clear, thank you

  • @Rod: as for the partial... It’s just a way to separate the code of a class into two blocks, and it can be in separate files. It is usually used for tool-generated code, in which the tool generates the class with partial so that the programmer can add more code in this same class from within another file... so if the tool generates the file again, the programmer’s code will not be affected. I don’t recommend using partial classes for code organization... if you see something like this being done, then something stinks.

  • Great example of how the virtual keyword works.

Show 1 more comment

6

Class is a structure/model representing a real-world object/purpose.

Examples:

class Veiculo {...}
class Animal {...}
class Pessoa {...}

Attributes are characteristics that the class has.

Example - A person has a name, date of birth, CPF, RG, marital status, etc...:

class Pessoa {
    public String Nome { get; set; }
    public Date DataNascimento { get; set; }
    ...
}

Methods are actions that the class can do.

Example - In the person class, we can have a Walk(), Sleep() action, etc. When it comes to programming, we can have methods like Save(), Delete(), Getbyid(), etc.

public class Pessoa {
   ...
   public void Andar(int qtdePassos);
   public boolean Salvar(Pessoa pessoa);
   ...
}

There are several attributes that we can associate to an attribute, method and class.

In the case of the attribute "VIRTUAL" it says that the method can be overwritten in the descending class (which it inherits from the main class), that is, it allows you to use the main class code or else ignore by rewriting the code in the inherited class.

There are other attributes like "Abstract" which says that the implementation will be done in the inherited class and not in the main one; "Static" says that the method/class does not need an instance created to access it; among others...

A good reference is: http://andrielleazevedo.wordpress.com/2011/08/11/conceitos-basicos-de-poo-programacao-orientada-a-objetos-para-c-parte-1/

4

CLASS: A class is a construction that allows you to create your own custom types by grouping variables of other types, methods and events. A class is like a model. It defines the data and behavior of a type. If the class is not declared static (STATIC), the client code can be used by creating objects from or instances from which they are assigned to a variable. The variable remains in memory until all references to it go out of scope. At this point, the CLR selects the variable as eligible to be discarded. If the class is declared static (STATIC), only one copy exists in memory and the client’s code can only access it through the class itself, not by a variable instance. For more information, see Static classes and static class members.

EX:

public class Person
{
    // Field
    public string name;

    // Constructor that takes no arguments.
    public Person()
    {
        name = "unknown";
    }

    // Constructor that takes one argument.
    public Person(string nm)
    {
        name = nm;
    }

    // Method
    public void SetName(string newName)
    {
        name = newName;
    }
}
class TestPerson
{
    static void Main()
    {
        // Call the constructor that has no parameters.
        Person person1 = new Person();
        Console.WriteLine(person1.name);

        person1.SetName("John Smith");
        Console.WriteLine(person1.name);

        // Call the constructor that has one parameter.
        Person person2 = new Person("Sarah Jones");
        Console.WriteLine(person2.name);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output:
// unknown
// John Smith
// Sarah Jones 

METHOD: A method is a block of code that contains a series of instructions. A program causes the instructions to be executed by calling the method and specifying all necessary arguments of the method. In C#, all instructions are executed by methods. The Main method is the entry point for each C# application and it is called by the CLR (Common Languege Runtime) when the program is started. Methods are declared in a class or struct , specifying - whether the access level as public or private, optional modifiers such as Abstract or Sealed, the return value, the method name. These parts are attached to the method signature.

abstract class Motorcycle
{
    // Anyone can call this.
    public void StartEngine() {/* Method statements here */ }

    // Only derived classes can call this.
    protected void AddGas(int gallons) { /* Method statements here */ }

    // Derived classes can override the base class implementation.
    public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }

    // Derived classes must implement this.
    public abstract double GetTopSpeed(); 
}

ATTRIBUTES: Attributes provide an efficient method of associating metadata or declarative information to code (assemblies, types, methods, properties and so on). Attributes provide a powerful method of associating metadata or declarative information with code (assemblies, types, methods, properties and so on). After an attribute is associated with a program entity, the attribute can be consulted at runtime using a technique called Reflection. For more information, see Reflexo (programming guide C#) . Attributes have the following properties: Attributes add metadata to your program. Metadata is information about the types defined in a program. All assemblies . NET contain a set of metadata describing types and their members. You can add custom attributes to specify any additional information needed. For more information, see Creating custom attributes (C# and Visual Basic). You can apply one or more attributes to small program assemblies, modules, or elements such as classes and properties. Attributes can accept arguments in the same way as methods and properties. Your program can examine metadata in other programs or your own metadata through reflection. For more information, see Accessing reflex attributes (C# programming guide).

Using attributes

Attributes can be applied to most code elements, although a specific attribute can restrict the types of elements to which it is applied. In C#, an attribute is specified by placing its name between brackets ([]) above the statement of the entity to which it can be applied. In Visual Basic, an attribute should be used between angular brackets (< >). It should appear immediately before the element to which it is applied, on the same line. In this example, the Serializableattribute attribute is used to apply a specific feature to a class:

[System.Serializable]
public class SampleClass
{
    // Objects of this type can be serialized.
}

Common uses for attributes The following list includes some of the common uses of attributes in the code:

  • Marking methods using the Webmethod attribute in Web Services to indicate that the method should be accessible through the SOAP protocol. For more information, see Webmethodattribute. -Describe how the domethod parameters perform marshaling when interoperate with native code. For more information, see Marshalasattribute. -Describe the COM properties of classes, methods and interfaces. Unmanaged code call with Dllimportattribute class. -Describe your Assembly in terms of version, title, description or trademark. -Describe which members of a class to serialize for persistence. -Describing as map between class members and XML nodes XML paraserialization. -Describe the safety requirements for methods. -Specifying the characteristics used to enhance security. -Controlling optimizations by the Just-In-Time compiler (JIT) so that the code remains easy to debug. -Getting information about the caller for a method.

I gave a summary, all links are here: Method,Attribute, Class

Browser other questions tagged

You are not signed in. Login or sign up in order to post.