Home > Back-end >  C# OOP Syntax Query [duplicate]
C# OOP Syntax Query [duplicate]

Time:10-09

I'm trying to get spun up on C#, so excuse this rudimentary question.

In the following code, I do not understand this statement var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data; Obviously, it's creating a variable named eventData of type StorageBlobCreatedEventData, but why are there parentheses around the class?

    public static class Function1
    {
        [FunctionName("EventGridTrigger")]
        public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation("C# Event Grid trigger handling EventGrid Events");
            log.LogInformation($"New event received: {eventGridEvent.Data}");

            if (eventGridEvent.Data is StorageBlobCreatedEventData)
            {
                var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data;
            }
        }
    }
}

CodePudding user response:

The parenthesis in that context is an object cast. The type it is passed in is a more generic type. The if(event.Data is StorageBlob... detects that it is of a more specific type, and if so then inside the if we know we can successfully cast it to that type. Now this example doesn't actually do anything with that variable, so a little nonsensical, but usually you'd then be able to do things like eventData.SomeMethodOnlyAvailableOnStorageBlob(). I.e. access properties and methods that are only declared on the specific StorageBlobCreatedEventData type which aren't available on the more generic type.

Generally it is unsafe to cast from a generic type to a more specific type. You need to perform a check first to ensure that it is the specific type before attempting the cast.

This is basically a feature detection pattern. If you see that a type implements a specific derived class or interface, then conditionally do something with that.

CodePudding user response:

The code (StorageBlobCreatedEventData) is an explicit cast.

So sometimes the compiler can't explicitly know which class you expect, so you need to tell it in this way. Or sometimes you might want to cast a child to a parent.

Taking the examples from the MS documentation https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions

// Create a new derived type.
Giraffe g = new Giraffe();

// Implicit conversion to base type is safe.
Animal a = g;

// Explicit conversion is required to cast back
// to derived type. Note: This will compile but will
// throw an exception at run time if the right-side
// object is not in fact a Giraffe.
Giraffe g2 = (Giraffe)a;
  •  Tags:  
  • c#
  • Related