Click here to Skip to main content
15,902,445 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi. I cant understand how this is working:

C#
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp_Practicing
{

    class Program
    {
        static void Main(string[] args)
        {
            Exception ex = new Exception();
            Console.WriteLine(ex.GetType().Name); // THIS LINE 

        }
    }
   
}


Could someone explain me ? Thanks!

What I have tried:

Asking question here in CodeProject.com
Posted
Updated 18-Jul-17 2:57am

Hi,

You can access that property because the method returns an object of type Type that represents the exception type.

I'm going to be more specific:

ex is an Exception, so you can access the GetType() method by calling ex.GetType(). That stamement is of type System.Type (link) that represents the type Exception. That type also has some other methods/properties, so you can access them by using the dot operator as you previously did with ex. So you can write (I'll split it here using parenthesis for didactic purposes, but they are not necessary).

C#
(ex.GetType()).Name
//--[1]--------[2]--


[1]: you get the instance of System.Type of the instance of the Exception object ex (see Richard MacCutchan's answer for more details about the GetType() method).
[2]: now you have an instance of an object of type System.Type (actually it does not matter how you got it, now you can actually use it): access the Name property of that instance. So you get "System.Exception" (I believe) because you asked the System.Type of an Exception object and that Type's name is "Exception".

That's what your code says.

Hope this helps.
 
Share this answer
 
v3
It is all described in the documentation: Object.GetType Method (System)[^].
 
Share this answer
 
Exception[^] is a class that inherits (like anything else at the end) from Object[^] class. That class has a method called GetType[^], that returns a object of Type[^] class, that has a property Name[^]...
 
Share this answer
 
This expanded form is :
Exception ex = new Exception();
Type typeInfo = ex.GetType();
Console.WriteLine(typeInfo.Name);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900