What is wrong with this C # method?

I use this method to get the file extension,

public string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".doc":
            case ".docx":
                return "application/ms-word";
        }
    }

When I compile it, I got an error BaseClass.ReturnExtension(string)': not all code paths return a value.. Any suggestion ...

+3
source share
8 answers

You need to add a condition defaultif you return from the statement switch.

// As SLaks mentioned, you should be case in-sensitive.
// Therefore, I'm comparing only the Lower Case version of the extensio

switch(fileExtension.ToLowerInvariant())
{
    case ".doc":
    case ".docx":
        return "application/ms-word";
    default:
        // You could also throw an Exception here if unknown extensions
        // are truly invalid (which seems to be the more popular choice)
        //
        // Since it looks like you're returning a content-type for a
        // download, I would default to octet-stream so the user would
        // just get a download window.
        return "application/octet-stream";
}
+18
source

You did not indicate that you should return a method if fileExtension is not ".doc" or ".docx". You can do this by adding a default case to the switch statement. Assuming other fileExtension values โ€‹โ€‹are invalid, you should throw an exception:

public string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".doc":
        case ".docx":
            return "application/ms-word";
        default:
            throw new ArgumentException(string.Format("Invalid fileExtension '{0}'.", fileExtension));
    }
}
+17
source

- switch.

default:
        Console.WriteLine("Default case");
        return "";
+4

, . , : .

while, if switch.

, , , (: string).

fileextension (doc, docx) .

  • default switch
  • catch-all return (return "text/plain"?)
+3

, , , Extension ".rtf" .

, "-", , "default:". , , ".doc" ".docx".

+1

, , fileExtension .xls. - switch:

public string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".doc":
        case ".docx":
            return "application/ms-word";
    }
    return "unknown";  // this path wasn't returning anything
}
+1

default break, break.

+1

$0.10, , , , , MIME (, "" ), octect, :

public string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".doc":
        case ".docx":
            return "application/ms-word";
        default:
            return "application/octet-stream";
    }
}

, , 5 , M $ MS-Word v30.1, ".docz", , MS-Word () , IE- , "application/ms-word".

0

Source: https://habr.com/ru/post/1741925/


All Articles