🚀 The #1 C# Interview Question: Master Extension Methods Have you ever looked at a built-in class in .NET and thought, "I wish this class had just one more specific method"? Since we don't own the source code for the .NET Framework or third-party libraries, we can't just open the file and type it in. This is exactly where Extension Methods come to the rescue. 💡 The Problem: "RightSubString" The standard string class provides Substring(), which is great for taking characters from the left. But if you want to get the last 5 characters (the right side), there is no direct method like RightSubstring(5). Since the string class is sealed and part of the framework, we can't modify it. 🛠️ The Solution: The Extension Method We can "inject" a new method into the string class using this specific syntax: using System; namespace MyExtensions { // 1. The class MUST be static public static class StringExtensions { // 2. The method MUST be static // 3. Use 'this' before the first parameter to bind it to the String class public static string RightSubString(this string value, int count) { if (value.Length <= count) return value; return value.Substring(value.Length - count); } } } 🏃 See It In Action Once you’ve defined the method above, it appears in IntelliSense as if it were a native part of the string class! string test = "hello world"; // Standard .NET method string left = test.Substring(0, 5); // Returns "hello" // YOUR CUSTOM extension method! string right = test.RightSubString(5); // Returns "world" Console.WriteLine(left); Console.WriteLine(right); 📝 3 Golden Rules for the Interview If an interviewer asks you about Extension Methods, make sure you mention these three points: Statics Only: Both the class and the method must be declared as static. The "this" Keyword: This is the magic ingredient. The first parameter must start with this [ClassName]. This tells the compiler which class you are extending. Namespace Scope: To use the extension, you must import the namespace where the static class resides. #DotNet #Programming #Coding #StringExtensions #CodingTips #TechPost #ViralTech #LearnCode #SoftwareDevelopment
C# Extension Methods: RightSubString Example
More Relevant Posts
-
React Interview Question You Must Know: useState vs useReducer Explained If you're preparing for React interviews or building scalable applications, understanding the difference between useState and useReducer is a must! 🔹 useState useState is the simplest way to manage state in functional components. 👉 Best suited for: Simple state (strings, numbers, booleans) Independent state updates Quick and readable logic ✅ Example: import React, { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } 🔹 useReducer useReducer is used for managing complex state logic and multiple related state transitions. 👉 Best suited for: Complex state (objects, multiple values) When next state depends on previous state Centralized logic (like Redux pattern) ✅ Example: import React, { useReducer } from "react"; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> </div> ); } ⚡ Key Differences 🔸 useState Simple and easy to use Direct state updates Less boilerplate 🔸 useReducer Better for complex logic Uses reducer function + dispatch More scalable and predictable 💡 When to use what? ✔ Use useState → when state is simple ✔ Use useReducer → when state logic becomes complex or interdependent 🔥 Pro Tip: If you find yourself writing multiple setState calls with complex conditions, it's a strong signal to switch to useReducer. 💬 What do you prefer in your projects — useState or useReducer? Let’s discuss! #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #ReactHooks #CodingInterview
To view or add a comment, sign in
-
-
🎥 .NET Core Interview Prep — Video #4 🚨 If you don’t understand Service Lifetimes, you WILL get stuck in .NET interviews Last video we broke down Middleware… 👉 Today we’re unlocking a concept interviewers love to grill you on 💡 Service Lifetimes in .NET Core (Simple Explanation) When you register services in Dependency Injection, you’re also deciding: 👉 How long should this object live? There are 3 key lifetimes you MUST know 👇 🟢 AddSingleton ✔️ Created once ✔️ Same instance used throughout the application ✔️ Best for: caching, configuration, shared resources 🔵 AddScoped ✔️ Created once per request ✔️ Same instance reused within a single HTTP request ✔️ Best for: database contexts (like DbContext) 🟡 AddTransient ✔️ Created every time it is requested ✔️ New instance everywhere ✔️ Best for: lightweight, stateless services 💻 Simple Example (Interview Ready): builder.Services.AddSingleton<IMyService, MyService>(); builder.Services.AddScoped<IRequestService, RequestService>(); builder.Services.AddTransient<IHelperService, HelperService>(); --------------------------------------------------------------------------------- 🧠 Quick Trick to Remember: 🟢 Singleton → One for entire app 🔵 Scoped → One per request 🟡 Transient → New every time --------------------------------------------------------------------------------- ⚠️ Common Interview Trap: 👉 Injecting Scoped service into Singleton ❌ (Can cause runtime issues — know WHY!) 💬 Interview Question for YOU: Which lifetime would you choose for a logging service and why? 🤔 👇 Drop your answer in comments 🎯 Next Video: How to enable static files in the .net core👀 #DotNet #DotNetCore #CSharp #DependencyInjection #SoftwareEngineer #CodingInterview #TechCareers #Developers #BackendDevelopment #SystemDesign #Programming #LearnToCode #InterviewPreparation #CleanCode
To view or add a comment, sign in
-
🚀 .NET Interview Prep – Action Method Return Types (Quick Guide) If you're preparing for ASP.NET Core interviews, understanding action method return types is a must 👇 🔹 IActionResult Used when returning multiple HTTP responses like Ok(), NotFound(), BadRequest() 🔹 ActionResult ✅ (Recommended) Strongly typed + flexible Returns both data and status codes 🔹 Direct Types (string, int, Model) Automatically serialized to JSON with 200 OK 🔹 Async Return Types Task<IActionResult> Task<ActionResult<T>> ✅ (Best Practice) 💡 Best Practice: Use ActionResult<T> or Task<ActionResult<T>> for clean, scalable, and production-ready APIs 🎯 Interview Tip: ActionResult combines strong typing with flexibility, making it ideal for modern APIs ❓ Question for You: 1. Is IActionResult strongly typed? (Yes/No)🤔 2. Is ActionResult<T> preferred over IActionResult? (Yes/No) 🤔 3. Does ActionResult<T> improve performance? (Yes/No)🤔 #DotNet #ASPNetCore #WebAPI #BackendDevelopment #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
“Sometimes in interviews, the interviewer might ask: RestTemplate vs WebClient vs RestClient — which one should you use?” 🤔 Most developers know RestTemplate… Few understand WebClient… Very few have explored RestClient (Spring 6). Let’s break it down clearly 👇 🚀 1️⃣ RestTemplate (Legacy) 👉 Classic synchronous HTTP client in Spring ⚙️ How it works: ✋ Blocking (thread waits for response) ✋ Simple and easy to use ✋ Widely used in older applications 💻 Example: RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject( "https://lnkd.in/daRCyQjR", String.class ); ⚠️ Limitations: ✋ Blocks threads → not scalable under high load ✋ Deprecated in favor of modern alternatives ⚡ 2️⃣ WebClient (Reactive) 👉 Part of Spring WebFlux (Non-blocking client) ⚙️ How it works: ✋ Non-blocking (uses reactive streams) ✋ Supports async + streaming ✋ Built for high-throughput systems 💻 Example: WebClient webClient = WebClient.create(); Mono<String> response = webClient.get() .uri("https://lnkd.in/daRCyQjR") .retrieve() .bodyToMono(String.class); 👍 When to use: ✋ High concurrency systems ✋ Reactive applications ✋ Streaming APIs 🆕 3️⃣ RestClient (Spring 6+) 👉 Modern replacement for RestTemplate ⚙️ How it works: ✋ Synchronous (blocking) ✋ Fluent, clean API ✋ Built on top of WebClient internally 💻 Example: RestClient restClient = RestClient.create(); String response = restClient.get() .uri("https://lnkd.in/daRCyQjR") .retrieve() .body(String.class); 🎯 Which One Should You Choose? 👉 Existing legacy app → RestTemplate (but avoid new usage) 👉 High-scale / reactive → WebClient 👉 Modern sync apps → RestClient 🧠 Interview Tip If interviewer asks: ❓ “Why not RestTemplate?” Answer: It’s blocking and not actively enhanced. Spring recommends WebClient or RestClient for modern applications. ⚡ Final Thought The choice is not about “which is better”… 👉 It’s about use case and scalability needs. Which one are you currently using in your projects — RestTemplate, WebClient, or RestClient? 👇 #SpringBoot #Java #BackendDevelopment #Microservices #WebClient #SystemDesign #TechInterview
To view or add a comment, sign in
-
About 70% of my interview questions felt… familiar. Not because I got lucky - but because I prepared the right way 👇 A few months ago, I passed 7 technical interviews. And one pattern kept repeating: 👉 The same questions 👉 The same concepts 👉 The same traps That’s exactly why I spent months building a .NET Interview Preparation Kit - not theory, but real questions that actually show up in interviews. Today, I moved everything into my private Skool community and decided to make it 100% FREE. 🆕 New update: I just added 20 Array questions with answers and source code. Inside, you’ll get: • 200+ real .NET interview questions • C#, ASP.NET, EF Core, SQL, LINQ, Async, DI • Design Patterns & System Design (practical, not academic) • PDF + GitHub repository • 2 eBooks (including the brand-new LinkedIn Handbook) • Source code from my YouTube videos & blog posts • Direct access to me + other developers • Continuous updates & discounts on future content 👉 Get the Interview Kit for FREE: https://lnkd.in/dn-iW-Rt 👉 Join the FREE community: https://lnkd.in/gu_5HiMD If you’re preparing for a .NET interview, this can save you weeks of unfocused prep. __ 📌 Don't miss the next newsletter issue, 20,000 engineers will read it, join them: thecodeman.net ♻️ Repost to others. 📂 You can save this post for later, and you should do it. ➕ Follow me ( @Stefan Đokić ) to learn .NET and Architecture every day.
To view or add a comment, sign in
-
-
🚀 365 Days Interview Challenge – Day 32 🎯 Experience Level: Advanced ❓ Interview Question: "Can you explain how JavaScript's prototype chain works? How does it affect property lookup and inheritance, and what are the performance implications of a long chain?" ✅ Explanation: Every JavaScript object has a hidden link to another object called its "prototype." That prototype object also has its own prototype. This creates a chain, like a family tree. When you ask for a property (like `obj.name`), JavaScript looks for it on the object itself. If not found, it goes up the chain to the prototype, then the prototype's prototype, and so on. It stops at the end of the chain (where the prototype is `null`). This is how inheritance works in JavaScript. 💡 Real-world Example: Think of a company hierarchy. You (an Employee) ask your Manager for a project file. If your Manager has it, you get it. If not, they ask their Director. The Director asks the VP, and so on, until someone has the file. The chain of command is the prototype chain. 🧠 Best
To view or add a comment, sign in
-
Most .NET developers don’t fail interviews because they lack knowledge. They fail because they answer like juniors. Example: Question: What is async/await? Weak answer: “It helps with asynchronous programming and improves performance…” Strong answer: “It doesn’t make code faster. It frees up threads. That’s critical in high-concurrency systems like web APIs…” Same knowledge. Different level. If your answers sound like the first one. You already know why you’re getting rejected. Based on real interview experience, I’ve compiled key questions into a FREE PDF. Access it here: https://lnkd.in/g9eVsGRP
To view or add a comment, sign in
-
📌 Java Interview Questions ------- 📌 Question 10: What does the `final` keyword mean in Java? A) Method can be overridden B) Variable can’t be changed C) Class can be extended D) None of the above ------- 📌 Question 11: Which of the following is not a Java keyword? A) static B) transient C) void D) include ------- 📌 Question 12: Which is faster: StringBuilder or String Buffer? A) String B) String Buffer C) StringBuilder D) Both same ------- 💡 Save this for your interviews! #JavaQuiz #JavaInterviewPrep #Keywords #Performance #FinalKeyword #AshokIT #Developer #Codinglife
To view or add a comment, sign in
-
📌 Java Interview Questions ------- 📌 Question 10: What does the final keyword mean in Java? A) Method can be overridden B) Variable can’t be changed C) Class can be extended D) None of the above ------- 📌 Question 11: Which of the following is not a Java keyword? A) static B) transient C) void D) include ------- 📌 Question 12: Which is faster: StringBuilder or String Buffer? A) String B) String Buffer C) StringBuilder D) Both same ------- 💡 Save this for your interviews! #JavaQuiz #JavaInterviewPrep #Keywords #Performance #FinalKeyword #AshokIT #Developer #Codinglife
To view or add a comment, sign in
-
Thought I was done. Tested it. Wasn't done. Two things broke in real use: 1.Fabrication - Interview prep was generating STAR stories extrapolated from my CV. Looked fine. Was completely made up. Fixed it — now it asks you to recall real experiences and structures those. If you haven't built a story bank yet, it tells you that instead of inventing one. 2. Token bloat - Ran a proper analysis across all 7 modes. Outreach, scanning, story sessions were loading the full CV for no reason. Built a digest for light modes — cut context by 45–60% on those commands. Also added an onboarding flow. If there's no profile or experience on file, it doesn't guess — it asks specific questions to build a scaffold you can actually work from. Not perfect but closer to honest now. Suggestions or feedbacks are welcome. Github Link - https://lnkd.in/g2FFFK8K #BuildingInPublic #AITools #JobSearch #ClaudeCode #SideProject #CareerTech #AIAgent #AI #AIAutomation
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development