I have a regex that I am trying to evaluate the value of in the following method:
private void ValidateText()
{
if ((!IsOptional && Text == string.Empty))
{
SetIsValid(false);
}
else
{
if (this.ValidationRegex != null)
{
SetIsValid(this.ValidationRegex.IsMatch(this._text));
}
else
{
SetIsValid(true);
}
}
}
Where:
private Regex ValidationRegex { get; set; }
Now, when it gets to this.ValidationRegex != null I hover over the ValidationRegex value and {NULL} is displayed, so I expect my line to return false and go into the else statement.
Instead, this line returns true and I can't understand why. I have attached a screenshot of this below:
I can't seem to work it out (This is not a threading thing)
The pattern you have in the Regex object is NULL.
var ValidationRegex = new Regex("NULL");
This regex is looking for a string NULL in the input string (like This value is NULL.), and the ValidationRegex object is initialized and is not null. So, if evaluates to true.
Just a note: you can't check if a value is NULL using regex.
According to the documentation, the ToString() of Regex class (which is what Visual Studio is displaying) returns the regular expression pattern that was passed into the Regex constructor.
So I would assume your pattern is NULL.
Related
I have an email template
For example this
Hello #FirstName# #LastName#
I have an object that comes from a parameter with properties
I need to iterate all object properties and replace all words that matched the property name quoted with "" with property value.
So, for example, I have an object with FirstName and LastName, I need to iterate this object property and change #FirstName# and #LastName# in email.
I try to write this method
private string ReplaceTemplateValues(object input, string emailTemplate)
{
foreach(var property in input.GetType().GetProperties())
{
var replacedTemplate = emailTemplate.Replace($"#{property.Name}#", property);
}
}
But how I can get property value in var replacedTemplate = emailTemplate.Replace($"#{property.Name}#", property);
and return whole replaced string?
I would recommend to rurn it the other way round: look for #...# in the template string and replace it by the values from the input object. This will also behave nice if you happen to have #X# in the template but there is no property X.
To extract the property names from the template, you can use regular expressions:
private string ReplaceTemplateValues(object input, string emailTemplate)
{
return Regex.Replace(emailTemplate, #"#(?<prop>\w+)#", m =>
{
var property = input.GetType().GetProperty(m.Groups["prop"].Value);
if (property != null)
{
var value = property.GetValue(input);
if (value != null)
return value.ToString();
}
return "";
});
}
Explanation of the Regex (see also documentation)
# will match a literal "#"
(?<prop>\w+) will match at least one (that's the +, see quantifiers) "word character" (that's the \w, see character classes - I assume that your property names are represented as such) and put the result in a group named "prop" (see named subexpressions)
# will match another literal "#"
m.Groups["prop"].Value will get you the matched group, i.e. the property name.
I am stumped on how to figure out the condition. Basically I have information from a list into a string to use Contains and Regex. I need to figure out if the user selected the "Other" option and if so then do something. However in the same list there are additional values to choose from that start with "Other" as well.
Example Data:
Fire Material
Other
Other Chemical
Example Code:
if(MaterialList.ToString().Contains("Other"))
{
"Do This If Other Is Selected";
}
else
{
"Do That If Other Isn't Selected";
}
It works fine if the user selects just "Other" however, if the user doesn't select "Other" but selects "Other Chemical" the condition still returns true.
I have also tried the following and it behaves the same:
public static bool ExactMatch(string input, string match)
{
return Regex.IsMatch(input, string.Format(#"{0}", Regex.Escape(match)));
//actually doesn't find the exact match - just a portion of the string
}
Probably Contains or Match shouldn't be used but not sure how to solve the problem.
Looks like you could use Linq instead:
if (MaterialList.Any(m => m == "Other"))
...
You can use String.EndsWith() function in your case
From MSDN:
Determines whether the end of this string instance matches the
specified string.
try this:
if(MaterialList.ToString().EndsWith("Other"))
{
"Do This If Other Is Selected";
}
else
{
"Do That If Other Isn't Selected";
}
Why not use
public static bool ExactMatch(string input, string match)
{
return input == match;
}
or you're sick by do-everything-with-regex?
Thanks all. Figured it out.
if(MaterialsList.ToString().Split('\t').Contains("Other"))
if i have a master property string for example:
public String SharedInfo
{
get { return (String)Session["SharedInfo"]; }
set { Session["SharedInfo"] = value; }
}
and a label in an content page, i check if the string is empty by doing:
if(Master.SharedInfo == null)
now my question is: why does if(Master.SharedInfo == "") not work, because the SharedInfo is a string right?
There is a handy method that "catches" both
if (String.IsNullOrEmpty(Master.SharedInfo)) {
...
}
null and "" are not equal. null means no string at all. "" is a string of length 0.
string s = null;
int i = s.Length; // <-- Throws null reference exception
But
string s = "";
int i = s.Length; // OK, i => 0
"" and String.Empty are equivalent. Some people state that you should always use String.Empty instead of "", but it makes really no difference.
UPDATE
Equal string constants are interned by the compiler, i.e. the compiler stores equal constants only once. You can make a simple test (in response to #BobTodd's comment),
string s = "";
Console.WriteLine(Object.ReferenceEquals(s, "")); // --> true
Console.WriteLine(Object.ReferenceEquals(s, String.Empty)); // --> true
For the sake of completeness (according to #JoelEtherton's comment). Starting from .NET Framework 4.0 you can test
if (String.IsNullOrWhitespace(Master.SharedInfo)) {
...
}
This will catch strings like " " or "\t" as well.
In c#, an empty string "" is not null. It's an actual string, with length equals to zero.
You can use string.IsNullOrEmpty(string stringToTest) to check both null and empty strings.
String.Empty ("") and null are quite different
It depends wholly on what has been written to Session["SharedInfo"].
If nothing has, then it will be null, otherwise its the value written, which could be an empty string or null.
To be sure use String.IsNullOrEmpty(string #string)
Just a quick one:
string firstline;
if (firstline == null) {
System.Console.WriteLine("String empty!");
}
In theory if there is no value in "firstline", the console should out put "String empty!"?
This doesn't even compile because of:
Use of unassigned local variable 'firstline'
When you say you don't get any output but the program compiles and runs just fine, you are not showing us your real code.
However, if firstline is not a local variable but a member variable of the surrounding class, it will be automatically initialized with null. In general, all member variables of a class are initialized with default(T) where T is the type of the member variable.
You can't compile in VS with error: Use of unassigned local variable 'firstline' !
Try assign null before!
EDIT
or
class Program
{
static string firstline; # with static you can compile and got your behaviour
static void Main(string[] args)
{
if (firstline == null)
{
System.Console.WriteLine("String empty!");
}
Console.ReadKey();
}
}
In default they are not null. If you want it null by default use this:
static string firstline;
static void Main(string[] args)
{
if (firstline == null)
{
System.Console.WriteLine("String empty!");
}
}
But I suggest using this one:
static void Main(string[] args)
{
string firstline = null;
// or this:
//string firstline = String.Empty;
if (String.IsNullOrEmpty(firstline))
{
System.Console.WriteLine("String empty!");
}
}
In both ways you can get riddle of
Use of unassigned local variable 'firstline'
Yes that will behave as you expect and should print out to the console. You might find that the console application closes too quickly for you to read the result though if you've not got any following code.
Also null and "" (or String.Empty) often mean the same thing, so a more command way to do this is:
if(String.IsNullOrEmpty(firstline))
{
Console.WriteLine("String is empty!");
}
Your terminology makes it sound like you are a little confused.
A null string is precisely that - the absence of the value. It is not an empty string, it is a string with no value.
An empty string is a zero length string, "" or string.Empty. This is not null as it does have a value, but the value is zero length.
Often you want to treat the null and empty values the same, in which case you might use the check
if (string.IsNullOrEmpty(firstline))
{
System.Console.WriteLine("String is null or empty!");
}
Your code is not correct, Use of unassigned local variable 'firstline'. You can assign it with any value to test. If you want to check if it is an empty string, a better way is:
string firstline = null; //change to "" to test
if (string.IsNullOrEmpty(firstline))
{
System.Console.WriteLine("String empty!");
}
here are my 2 cents:
if (firstline == (string)null) throw new ArgumentNullException("firstline"); //value is null
if (firstline.Length == 0) throw new ArgumentOutOfRangeException("firstline", "Value is empty"); // string.Empty
I found this by using Pex and Moles
What is needed to make String.IsNullOrEmpty() count whitespace strings as empty?
Eg. I want the following to return true instead of the usual false:
String.IsNullOrEmpty(" ");
Is there a better approach than:
String.IsNullOrEmpty(" ".Trim());
(Note that the original question asked what the return would be normally hence the unsympathetic comments, this has been replaced with a more sensible question).
.NET 4.0 will introduce the method String.IsNullOrWhiteSpace. Until then you'll need to use Trim if you want to deal with white space strings the same way you deal with empty strings.
For code not using .NET 4.0, a helper method to check for null or empty or whitespace strings can be implemented like this:
public static bool IsNullOrWhiteSpace(string value)
{
if (String.IsNullOrEmpty(value))
{
return true;
}
return String.IsNullOrEmpty(value.Trim());
}
The String.IsNullOrEmpty will not perform any trimming and will just check if the string is a null reference or an empty string.
String.IsNullOrEmpty(" ")
...Returns False
String foo = null;
String.IsNullOrEmpty( foo.Trim())
...Throws an exception as foo is Null.
String.IsNullOrEmpty( foo ) || foo.Trim() == String.Empty
...Returns true
Of course, you could implement it as an extension function:
static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim()));
}
}