'Generic Method - Cannot implicitly convert type 'string' to T
May be a simple question..
I have an interface:
public interface ISanitizer
{
T Sanitize<T>(T data_);
}
And an implementing class:
public class BasicFilenameSanitizer : ISanitizer
{
private readonly String m_replacementCharacter = String.Empty;
public BasicFilenameSanitizer(String replacementCharacter_)
{
if (replacementCharacter_ == null)
{
throw new ArgumentNullException("replacementCharacter_");
}
m_replacementCharacter = replacementCharacter_;
}
public virtual T Sanitize<T>(T filename_)
{
if (filename_ == null)
{
throw new ArgumentNullException("filename_");
}
Regex invalidCharacterRegex =
new Regex(String.Format("[{0}]", Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()))));
//error occurs here
return Regex.Replace(filename_.ToString(), invalidCharacterRegex.ToString(), m_replacementCharacter);
}
}
Solution 1:[1]
In my particular case the following code generated the same error:
return (T) someData;
What helped me out - double cast with object:
E.g:
static T MyFunction<T>() {
string s = "test";
if (typeof(T) == typeof(byte[]))
return (T)(object)System.Text.Encoding.ASCII.GetBytes(s);
else if (typeof(T) == typeof(string))
return (T)(object)s;
else throw new Exception();
}
...
var ba = MyFunction<byte[]>();
var bs = MyFunction<string>();
Solution 2:[2]
Your problem is that the method Sanitize<T> hasTas the return type, but the method actually returns astringfromRegex.Replace`.
Try changing the method to return a string instead:
public virtual string Sanitize<T>(T filename_)
That means you need to change your method in the interface to return string as well.
Solution 3:[3]
Adam,
your interface is incorrect, try:
public interface ISanitizer<T, TA>
{
T Sanitize(TA data);
}
public class BasicFilenameSanitizer<T, TA> : ISanitizer<T, TA>
{
public virtual T Sanitize(TA data)
{
throw new NotImplementedException();
}
}
public class Test : BasicFilenameSanitizer<int, string>
{
public override int Sanitize(string data)
{
return data.Length;
}
// a little test func...
public void TestFunc()
{
int result = this.Sanitize("fred");
Console.Write(result);
}
}
[edited] - to add example.. cheers..
Solution 4:[4]
string result = "test";
return (T)Convert.ChangeType(result, typeof(T));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefan Michev |
| Solution 2 | Øyvind Bråthen |
| Solution 3 | |
| Solution 4 |
