2

I have boil it down to a simple example:

using System;
using System.Data;


class MyProgram
{
    void DoStuff(DbType t)
    {

    }

    public MyProgram()
    {
        DoStuff(SqlDbType.Int);
    }
}

class Program
{
    public static void Main(string[] args)
    {
        MyProgram p = new MyProgram();
    }
}

Why do I have to call it this way?

DoStuff((DbType)SqlDbType.Int);

Is it simply because they are just two enumerators and there's something behind the scenes linking them together?

cheers, Alex

Alex
  • 2,247
  • 1
  • 27
  • 37

1 Answers1

3

SqlDbType and DbType are two entirely separate enumerations. They are just as compatible as enum Colors and enum DayOfTheWeek would be, as far as the compiler can tell.

You need to perform the cast to tell the compiler "I know these are different types, but I want you to treat one as the other anyhow."

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Source: MSDN (emphasis mine)

Note that MSDN does not document any specific underlying values for SqlDbType or DbType, so even if SqlDbType.BigInt and DbType.BigInt have the same underlying value today, there is not a documented guarantee that it will stay that way, or that it is that way on every .NET implementation.

However MSDN does make the following guarantee

When setting command parameters, the SqlDbType and DbType are linked. Therefore, setting the DbType changes the SqlDbType to a supporting SqlDbType.

The best way to approach your code would be

DoStuff(DbType.Int);
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • have marked as answered, thanks, another question here: what if I just use DBType as transient, and the source is (DbType)SqlDbType.Int and the destination receives the DbType but then casts back to SqlDbType? Is this guaranteed to always have the same values? – Alex Oct 12 '15 at 05:02
  • If you cast (SqlDbType)(DbType)SqlDbType.Int there is no explicit guarantee that you will get the same SqlDbType out that you started with. In reality you probably will, at least for values that are common to SqlDbType and DbType, but the framework does not make that guarantee. – Eric J. Oct 12 '15 at 05:05