Skip to content
Advertisement

using in C# vs. import in Java

I am coming from Java and C++ background. However, I am doing a C# application at the moment and one thing made me confused.

In Java when I import a package, it means I can access the classes that are placed in that package. For example, here I imported the ArrayList class from package java.util.

import java.util.ArrayList;

class ArrayListUtilization {
    public static void main(String[] args) {

        ArrayList<Integer> myList = new ArrayList<>(3);
        myList.add(3);
        myList.add(2);
        myList.add(1);

        System.out.println(myList);
    }
}

Recently I had a problem in my c-sharp app, that I asked here. The funny part in my point of view is, when I added the following snippet of code:

var accountDbContext = services.GetRequiredService<AccountDbContext>();
accountDbContext.Database.EnsureCreated();
var accountDbCreator = accountDbContext.GetService<IRelationalDatabaseCreator>();
accountDbCreator.CreateTables();

I saw an error as following:

enter image description here

Error CS1929 ‘AccountDbContext’ does not contain a definition for ‘GetService’ and the best extension method overload ‘ServiceProviderServiceExtensions.GetService(IServiceProvider)’ requires a receiver of type ‘IServiceProvider’

and from the error text, I understood accountDbContext object does not have GetService function. But when I press on show potential fixes, then it suggests me to add a using statement.

enter image description here

And it was the real fix. However, my question is what is the effect of this using statement on my object? The object is an instantiation of its class. How can adding a using statement effect on my object and add a function to it?

Advertisement

Answer

Note that what you are actually calling an extension method here:

accountDbContext.GetService<IRelationalDatabaseCreator>();

accountDbContext does not have a method called GetService. GetService is declared in AccessorExtensions, and the above line is just syntactic sugar for:

AccessorExtensions.GetService<IRelationalDatabaseCreator>(accountDbContext);

Now it should make sense that you need to add a using directive for the class in which the extension method is declared, in order to access the extension method.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement