Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

c# recognize sql uniqueidentifier

I have a method that I want to use differently based on the type of input. This is what I have:

public static DataTable GetS(string source = null, string customer = null)
    {
        if (source != null && customer == null) 
        {
            return GetDataTableFromQuery("db.GetS", new object[] { "@source", source });
        }
        else if (source == null && customer != null)
        {
            return GetDataTableFromQuery("db.GetS", new object[] { "@customer", customer });
        }
        else
        {
            throw new Exception("Bad input. Call GetS with GetS(source) or GetS(null,customer).");
        }
    }

The sp looks like this:

CREATE PROCEDURE [db].[GetS]

    @source as nvarchar(128) = NULL,
    @customer as nvarchar(128) = NULL

AS
BEGIN
IF @customer IS NULL
BEGIN
    SELECT 
        *
    FROM 
        db.S
    WHERE
        [Source] = @source
END
IF @source IS NULL
BEGIN
    SELECT 
        * 
    FROM 
        db.S
    WHERE 
        customer = @customer
END

END

This works fine for GetS(source) and GetS(null,customer) but I have 2 issues.

  1. it goes bad if someone were to call with GetS(customer)
  2. it doesn't look very pretty..

is there some way of doing something like this(pseudo-code):

public static DataTable GetS(string input)
{
    if(input is sql-uniqueidentifier)
    {
        return GetDataTableFromQuery("db.GetS", new object[] { "@source", input});
    }
    else
    {
        return GetDataTableFromQuery("db.GetS", new object[] { "@customer", input]);
    }
}

or is there a better way? (sure, I could make 2 separate methods, but I'd like to make it work with just one Get-method. Feels weird if I make a GetSBySource or something).

Upvotes: 0

Views: 115

Answers (1)

BendEg
BendEg

Reputation: 21088

In your case, why not write two methode, this is not weird!!? I thing using two methods is the best way.

  1. public static DataTable GetSBySource(Guid source)
  2. public static DataTable GetSByCustomer(string customer)

This would make your API ways more usable and clear.

If you know, that one time you need it to pass an Uniqueidentifier, you could also make it generic:

public static DataTable GetS<T>(string input)
{
    if(T is Guid)
    {
        return GetDataTableFromQuery("db.GetS", new object[] { "@source", input});
    }
    else
    {
        return GetDataTableFromQuery("db.GetS", new object[] { "@customer", input]);
    }
}

But then you should also make your input generic, because passing Guids as strings around, is not very nice...

Using bad method definitions, will cause a lot of problems, when changing the code. For example you need to pass a Guid to the method, which only accepts string, than refactoring or changing the code will be very hard. Futhermore the definition of a method, should describe it's usage...

Upvotes: 3

Related Questions