The compiler for normal string literal with valid escape sequence like \n,\t compiles without any error.
But the moment I use invalid escape characters like \s,\w the compiler shows an error.Yes,We can avoid the error by using verbatim string or escaping it with \\ but my question is
Do compiler validates the string literals for valid escape characters and if so is that it’s only purpose!
Yes, it obviously does, that’s why you get the error messages.
I don’t really understand this question. I am assuming you are wondering why the compiler doesn’t simply accept invalid escape sequences and treats them verbatim. This would indeed be a possibility but it would render the interpretation of string literals slightly inconsistent:
\xwould mean different things depending on the actual value ofx.At the very least, there’s no disadvantage in C#’s strict checking of escape sequence validity. And maybe it avoids errors due to typos and confusions arising from different numbers of consecutive backslashes.