I am trying to write a code where EntityCollection is the parameter of the method
but I don't know what is the proper coding
is there someone who can help me about this?
here is the sample code
//by the way, this is a wrong coding, I am just showing you, what is the thing that I want to do...
private void sampleMethod(EntityCollection a)
{
if (a.ToList().Count == 0)
{
//body
}
}
and when I call it, this is what it looks like
sampleMethod(employee.EducationalBackground);
The question is a little difficult to understand but I suppose you're looking for something like this:
private void sampleMethod(EntityCollection<Employee> employees)
{
foreach(var employee in employees)
{
// do something with every employee.EducationalBackground
}
}
Search for "c# Generics" for info about the EntityCollection<Employee>.
Search for "linq" for info about how to work with collections.
Related
This question already has answers here:
Passing a List into a method, modify the list within the method without affecting 'original'
(5 answers)
Closed 2 years ago.
Maybe someone can help me, I'm really stumped.
I have a class called TextFunc which contains 2 functions.
The first function read a filepath and return a List<string>.
The second function takes that List<string> as a argument and returns an float[,]. Within this function I remove the first item of the list since I'm not interested in the header.
My problem is that somehow my second function modifies the original List.
So If I display the the first item of the list before the second function it shows what I expect.
After the second function the first item is gone.
I can't figure out why since I'm not using a reference when passing the argument into the second function. I don't even call it the same name or anything within the second function.
My class containing the 2 functions look like this (only keeping the relevant parts):
class TextFunc
{
public static List<string> ParseText(string filePath)
{
List<string> lines = File.ReadAllLines(filePath).ToList();
//do some stuff
return lines;
}
public static float[,] txt2Array(List<string> txtList)
{
txtList.RemoveAt(0);
// do some stuff
return floatArray;
}
}
I call the functions like this from an buttonclick event inside the Form1.cs
public partial class BRkData : Form
{
public BRkData()
{
InitializeComponent();
}
private void BRkData_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
List<string> txtFile = TextFunc.ParseText(#"C:\org_data.res");
MessageBox.Show(txtFile[0]); // here it displays what I expect
float[,] floatArr = TextFunc.txt2Array(txtFile);
MessageBox.Show(txtFile[0]); // here the first item of the list is gone?
}
}
I even tried making a copy of the list inside the txt2Array function but it does not matter. Somehow it's like I send a reference to the list to this function without knowing it.
Think of it like this. There is a man called List (reference type object) who knows a list of good pubs. You have his phone number on a piece of paper.
Calling a method is like giving the phone number to someone else. They have it written on a different bit of paper, but the same man answers the phone.
Passing using the ref keyword would mean that you give the other person the same bit of paper. They could cross out the original phone number and put a new one in, and give it back to you.
I didn't know I had to use the ToList command when I tried to copy it inside the function.
List<string> txtList = txtList_org.ToList();
Thank you for clarifying and pointing me in the right direction!
I want to add a new form to an existing solution. The solution already has a Validator class, so I want to expand this class.
The Form I want to create contains a Textbox (for the input) and a Button. When the input is the correct format the submit button is enabled. The input must adhere to a certain regular expression: "^[A-Za-z]{2}[0-9]{5}$". I'm checking the input (on-the-fly) in the Form class like this:
private void inputTbx_TextChanged(object sender, TextChangedEventArgs e)
{
SubmitButton.IsEnabled = Validator.IsInputValid(inputTbx.Text, RegexExpression);
}
I've put the regular expression as a variable in the Form class. I put it here because it is relevant to the textbox of this form only.
private const string RegexExpression = "^[A-Za-z]{2}[0-9]{5}$";
Here's the validation code:
public static bool IsInputValid(string inputToBeChecked, string regexExpression)
{
if (inputToBeChecked == null || regexExpression == null)
{
return false;
}
var regex = new Regex(regexExpression, RegexOptions.None);
return regex.IsMatch(inputToBeChecked);
}
So far so good. It seems to work fine. But I want to unit test it like so:
[TestCase("aZ13579")]
public void ValidateInputOkTest(string input)
{
Assert.IsTrue(Validator.IsInputValid(input, RegexExpression));
}
But to do it like this I have to have a string in my ValidatorTest class similar to the Regular-expression used in the Form class. This doesn't seem like the right way to do it. What I really want to do is get the Regex expression from the form class, so I am sure it's the correct Regex-expression that I'm using. Otherwise the Regex-expressions could easily get out of sync.
Here are the questions:
What is best practice here?
How do I get to this expression? I've tried doing it using Reflection, but I get a Threadstat error because it's a GUI component. Should I move the Regular-expression? If so where to?
I'm thinking there must be a smart way to do this. A smart design perhaps. Suggestions and comments are welcome.
You're probably going to want to back up a step and start to research the 'MVVM' design pattern. When you hear people talk about putting no code in the code behind, testing like this is one of the big benefits (among many others).
MVVM is too big a topic to handle in a simple answer like this. I'd search around on the web, and I'm sure other people have some good tutorials.
Just to be clear, it can be a big learning curve, but it's totally worth it. MVVM is what makes WPF much much (MUCH) better than WinForms, rather than merely different.
Just to address your question a little more specifically, you won't be testing a GUI object like a Window or UserControl. You'll be testing a view model which is just a regular class.
Here's a simplified version of what you might see
public class MyScreenViewModel : INotifyPropertyChanged
{
private const string RegexExpression = "^[A-Za-z]{2}[0-9]{5}$";
public bool UserInputIsValid { get { stuff; } set { stuff; }}
public string UserInput { get { stuff; } set { stuff; ValidateUserInput();} }
private void ValidateUserInput()
{
if (UserInput == null)
{
return false;
}
var regex = new Regex(RegexExpression, RegexOptions.None);
UserInputIsValid = regex.IsMatch(UserInput);
}
}
A view model in MVVM is the real logic of your screen. It will expose simple properties that the view can bind to for display/input, but the view isn't necessary for testing the logic.
Then your test looks something like:
[TestCase("aZ13579")]
public void ValidateInputOkTest()
{
var vm = new MyScreenViewModel();
vm.UserInput = "SomeValidText";
Assert.IsTrue(vm.UserInputIsValid);
}
[TestCase("aZ13580")]
public void ValidateInputNotOkTest()
{
var vm = new MyScreenViewModel();
vm.UserInput = "SomeInvalidText";
Assert.IsFalse(vm.UserInputIsValid);
}
i have the following 3 examples which does the same thing
//case1 do it if the condition is valid
private void SetMultiplePropertyValues()
{
if (Keyboard.GetKeyStates(Key.CapsLock) == KeyStates.Toggled)
{
//do somthing
}
}
//case 2 return if the condition is not valid
private void SetMultiplePropertyValues()
{
if (Keyboard.GetKeyStates(Key.CapsLock) != KeyStates.Toggled) return;
//do somthing
}
//case 3 checking the condition in the calling scope
if (Keyboard.GetKeyStates(Key.CapsLock)== KeyStates.Toggled)
SetMultiplePropertyValues())
private void SetMultiplePropertyValues()
{
//do somthing
}
which one would you go with and why
They do not do the same thing because in the first two cases the name of the method is a lie; the method name should be SetValuesIfTheKeyStateIsToggled or TryToSetValues or some such thing. Don't say you're going to do a thing and then not do it. More generally: separate your concerns. I would choose a fourth option:
public void TryToFrob()
{
if (CanFrob()) DoFrob();
}
private bool CanFrob()
{
return Keyboard.GetKeyStates(Key.CapsLock) == KeyStates.Toggled;
}
private void DoFrob()
{
// frob!
}
Notice what is public and what is private.
This is a silly looking example because each one is so simple, but one can easily imagine a situation in which these methods are complex. Keep your policies and your mechanisms logically separated. The mechanism is "is the keyboard in a particular state?" The policy is "I have some conditions under which I can frob; we must never frob unless those conditions are met".
First of all, as we can see at code comments, they don't do the same thing. So I think that you're talking about code architecture rather than functionality.
Second, here in SO isn't about giving opinions, but I'll try say to you concrete things about these differences.
1- Common if approach
if (true == false)
{
return true;
}
vs.
2 - Single line if approach
if (true == false) return true;
Most of code convetions says to use the option 1, because they're easier to read and understant code, and avoid some mistakes. We need to also understand that convetions are not rules! so they're just convetions, but really try to avoid option 2 in most of the cases.
One more thing, some code convetions also says that's ok using option 2 when you need something very simple, like this given example which is really easy to read and understand. But take this like an exception from the 'rules'.
I am trying to convert the following iOS code into MonoTouch and cannot figure out the proper conversion for the #selector(removebar) code. Can anyone provide guidance about the best way to handle #selector (since I've come across that in other places as well):
- (void)keyboardWillShow:(NSNotification *)note {
[self performSelector:#selector(removeBar) withObject:nil afterDelay:0];
}
My C# code is:
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification,
notify => this.PerformSelector(...stuck...);
I am basically trying to hide the Prev/Next buttons that show on the keyboard.
Thanks in advance for any help.
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, removeBar);
where removeBar is a method defined elsewhere.
void removeBar (NSNotification notification)
{
//Do whatever you want here
}
Or, if you prefer using a lambda:
NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification,
notify => {
/* Do your stuffs here */
});
Stephane shows one way you can use our improved bindings to convert that.
Let me share an even better one. What you are looking for is a keyboard notification, which we conveniently provide strong types for, and will make your life a lot easier:
http://iosapi.xamarin.com/?link=M%3aMonoTouch.UIKit.UIKeyboard%2bNotifications.ObserveWillShow
It contains a full sample that shows you how to access the strongly typed data that is provided for your notification as well.
You have to take into account that:
[self performSelector:#selector(removeBar) withObject:nil afterDelay:0];
it's exactly the same that
[self removeBar];
The call to performSelector is just a method call using reflection. So what you really need to translate to C# is this code:
- (void)keyboardWillShow:(NSNotification *)note {
[self removeBar];
}
And I guess that also the notification subscription, that sums up to this code:
protected virtual void RegisterForKeyboardNotifications()
{
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification);
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification);
}
private void OnKeyboardNotification (NSNotification notification)
{
var keyboardVisible = notification.Name == UIKeyboard.WillShowNotification;
if (keyboardVisible)
{
// Hide the bar
}
else
{
// Show the bar again
}
}
You usually want to call RegisterForKeyboardNotifications on ViewDidLoad.
Cheers!
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
It is important to me that my syntax does not make other developers confused.
In this example, I need to know if a parameter is a certain type.
I have hit this before; what's the most elegant, clear approach to test "not is"?
Method 1:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (!(e.parameter is MyClass)) { /* do something */ }
}
Method 2:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.parameter is MyClass) { } else { /* do something */ }
}
Method 3:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Parameter = e.parameter as MyClass;
if (_Parameter != null) { /* do something */ }
}
Method 4:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Type = typeof(MyClass);
switch (e.parameter.GetType())
{
case _Type: /* do nothing */; break;
default: /* do something */; break;
}
}
[EDIT] Method 5:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
Which is the most straight-forward approach?
This is obviously a matter of personal opinion and style, so there's no right answer, but I think this is clearest:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
The == false is just more obvious than the !
I would go for 3 if you need the variable later or 1 if you don't need the variable.
2 is ugly because of the empty block.
However I think they all are straight-forward.
I would think just making an extension method would be a clear way of doing it:
public static bool CannotBeCastAs<T>(this object actual)
where T: class
{
return (actual as T == null);
}
You then simply make a check like so:
if(myObject.CannotBeCastAs<SomeClass>())
{
}
Methods 1 and 3 would be my picks, depending on what I actually wanted.
Method 1 "does something" if and only if the passed object is not of the expected type. This means the passed object could be null and still pass.
Method 3 "does something" if the passed object is not of the expected type, OR if the object is null. This is basically a one-pass check that you have a "valid" instance of the class to work with further.
So, whether I wanted 1 or 3 depends on what I was planning to do. Usually, when the variable isn't of the expected type or is null, I want to throw an exception. If I were happy with throwing just one type of exception (say just an ArgumentException), I'd use method 3. If I wanted to check for null separately and throw an ArgumentNullException, I'd use method 1 and add the null check.
Method 2 is functionally correct, but I'd rather invert the if condition as in Method 1, as an if block that does nothing is redundant.
I would never do Method 4. A switch statement taking the place of a simple if-else is unnecessary and confusing, especially in the manner you're using it.
To me, Method 1 is the most straight-forward, both on its own and by convention. This is the syntax I've seen the most if you just need to know if an object "is-a" certain class.
If you actually need to do something with the object "as-a" certain class, then Method 3 is the way to go.
Method 1 is the best in my view. It's very obvious what the code is doing and I can follow right along. Method 2 introduces unnecessary syntax that is easily corrected by Method 1. Method 3 requires me to think more than the other two (marginally, but still!), and it also uses extra space that isn't needed.
Remember code is written for people to read, and only after for machines to execute. Go with clarity every time.
If you want elegance and readability:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
bool isMyClass = e.parameter is MyClass;
if (!isMyClass) // or isMyClass == false
{
/* do something */
}
}
I've always tried my best not to put too much logic in a single line of code, specially if conditions. I think the type check and negation operator might be annoying to parse on first glance.
Method #5 (a different spin)
public static class TypeExtensions
{
public static bool IsNotTypeOf<T, X>(this T instance, X typeInstance)
{
return instance.GetType() != typeInstance.GetType();
}
}
// ...
if(e.parameter.IsNotTypeOf(MyClass)) { /* do something */ } ;
I would be of the opinion that braced functionality should always match whatever brace pattern is in use in your application. For instance, in the case of iteration or conditional blocks, if you use:
If (foo != bar)
{
//Do Something
}
well then this should be how you use brace patterned functionality at all times. One of my biggest bugbears with reading other peoples code (and this is especially true if they use CodeRush or Resharper) is the unnecessary terseness people add for no other reason than to display wizardry.
I am not saying the above is the best brace matching pattern however, use whatever one you feel comfortable with, what I would like to get across is that the pattern does not matter so much as the consistency of its use.
Personally, since C# is a terse language in comparison to, say VB.Net I would use long form statements or assignments (with the exception of var initialising) over more condense syntax to help aid later readability.
I like an approach used by one of the NUnit Assert's:
Assert.InstanceOf<MyType>(objectInstance);
BTW,
If you have a set of checks whether object is of specific type like:
if(objectInstance is TypeA)
{
// ...
}else
{
if(objectInstance is TypeC)
{
// ...
}
}
There should be some design issues like tied coupling between few types, so consider an other approach like injected map of associations or map like algorithm method per type
IDictionary<Type, Func<TParameter>>