Expecto
Expecto

Reputation: 521

c# - type used as a variable

I have a simple business manager facade that should just persist some inventory information. However I keep getting the error that "Home.Services.InventorySvc" is a type being used as a variable.

My facade code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Home.Domain;
using Home.Services;

namespace Home.Business
{
    public class InventoryMngr
    {
        public void Create(CreateInventory inv) 
        {
            Factory factory = Factory.GetInstance();
            InventorySvc invSvc =
            (InventorySvc)factory.GetService(
            (InventorySvc).Name);
            invSvc.CreateInventory(inv);
        }
    }
} 

The InventorySvc code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Home;
using Home.Domain;

namespace Home.Services
{
    public interface InventorySvc : IService
    {
        void CreateInventory(CreateInventory createinventory);
    }
}

Upvotes: 1

Views: 852

Answers (2)

Tim M.
Tim M.

Reputation: 54359

InventorySvc invSvc = (InventorySvc)factory.GetService((InventorySvc).Name);

This code should retrieve an instance of a type which implements InventorySvc. However, it looks like you are attempting to pass an instance of the type, which wouldn't make sense--the syntax is wrong and you haven't yet instantiated the type. Presumably, you don't even know the specific type yet, just the interface type. The factory and the interface have abstracted the implementation (usually a good thing).

In your example, the factory probably expects the name of the type as a string (I won't overcomplicate the answer by debating if that is a good thing or not). In return, the factory will instantiate an instance which implements InventorySvc and return it. Only then can you invoke instance members such as the "Name" property.

As a side note, interface names should start with an I in c#, e.g. IInventorySvc. This makes it much clearer to you and anyone who reads your code that it is an interface.

Also see: https://stackoverflow.com/a/681815/453277

Upvotes: 1

Guffa
Guffa

Reputation: 700192

You are using (InventorySvc).Name which is the same as InventorySvc.Name, so that would be accessing a static member of the InventorySvc class. As it's not a class but an interface, it can't have static members.

Upvotes: 3

Related Questions