I understand type conversion. For example:

class Person { } class Student : Person { } 

Implicit conversion:

 Person p = new Student(); 

Explicit conversion:

 Person p = new Person(); p = (Student)p; 

In this case, the compiler allows the conversion, but throws an exception when executed.

So when is explicit type conversion allowed in C # and how can this be demonstrated with this example?

  • five
    along the way there is a problem with materiel. A student is always a person, and a person is not always a student. Something like that, if on the fingers - rasmisha
  • Well, yes, this is understandable. The question is: if not here, where can an explicit conversion be applied? - pavel_vrn
  • Well, the opposite is true, either if you are sure that p is a student (well, either check (p instanceof Student), or whatever it is in the details) Person p = new Student (); Student s = (Student) p; Quite normal (p = (Student) p; probably meaningless string) - rasmisha
  • four
    Read this answer here . - mantigatos

1 answer 1

Explicit type conversion in C # is permissible in two cases :

A. Explicit conversion of arithmetic types. Example:

 double pi = 3.1415926; int entier = (int)pi; 

B. Class conversion within the inheritance hierarchy:

 Student s = (Student)person; // тут возможно исключение 

Notice that conversion between types that are not related in the inheritance hierarchy is not possible in C #:

 string s = (string)person; // ошибка компиляции 
  • one
    Yes, in Sharpe, you can sort of implement a type cast, or am I wrong? it is remembered on some question long ago were perverted
  • @rasmisha: yes you can . But this is not the type conversion that the TS asked for. Although the syntax is the same. - VladD
  • @VladD persuaded :) - rasmisha
  • @VladD, thank you very much. - pavel_vrn
  • @ Pavel Batishchev: please. - VladD 2:26 pm